forme-ruby 0.3.0-aarch64-linux-gnu

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/docs/README.md ADDED
@@ -0,0 +1,18 @@
1
+ # Forme Ruby Guides
2
+
3
+ These guides introduce native PDF rendering, then cover application integration,
4
+ development and release. Each guide states its prerequisites and includes runnable
5
+ examples. Begin with [installation](installation.md).
6
+
7
+ | Guide | You will learn |
8
+ | --- | --- |
9
+ | [Installation](installation.md) | Runtime requirements, Git/source installs and native packages. |
10
+ | [Rendering](rendering.md) | Binary results, CSS, fonts, diagnostics and errors. |
11
+ | [Rails](rails.md) | Explicit controller rendering and ownership of responses. |
12
+ | [Contributing](../CONTRIBUTING.md) | Build, test and review changes. |
13
+ | [GitHub setup](github-setup.md) | Repository protections, security and publishing setup. |
14
+ | [Security exceptions](security-exceptions.md) | Reviewed, inaccessible upstream advisory paths. |
15
+ | [Releasing](releasing.md) | Qualify packages and prepare trusted publishing. |
16
+
17
+ See [README](../README.md) for a quick example and [CHANGELOG](../CHANGELOG.md)
18
+ for version-specific changes. The gem remains independent of consumer applications.
@@ -0,0 +1,62 @@
1
+ # Setting Up the GitHub Repository
2
+
3
+ After reading this guide, you will know what is checked in and which GitHub and
4
+ RubyGems settings a maintainer must enable. These instructions prepare
5
+ `clearstackio/forme-ruby`; they do not authorize pushing or publishing.
6
+
7
+ ## Repository files
8
+
9
+ The repository includes an MIT license, contributor and security guides, issue
10
+ forms, a pull-request template, CODEOWNERS, Dependabot, CodeQL, dependency review,
11
+ and build/release workflows. Actions are pinned to full commit SHAs; Dependabot
12
+ proposes updates. CI runs on pull requests, master pushes and a weekly schedule.
13
+ PR jobs do not receive publishing credentials. Checkout does not persist tokens.
14
+
15
+ ## Configure GitHub after an authorized push
16
+
17
+ 1. Set the description to “Native HTML and print CSS to PDF for Ruby and Rails,
18
+ powered by Forme.” Use topics `ruby`, `rails`, `pdf`, `rust`, `html-to-pdf`.
19
+ 2. Enable Issues and private vulnerability reporting. Enable the dependency
20
+ graph, Dependabot alerts, secret scanning and push protection where available.
21
+ CodeQL is provided as an advanced workflow for Ruby, Rust and GitHub Actions; do not also enable
22
+ CodeQL default setup.
23
+ 3. After the first successful run, protect `master` with a ruleset requiring pull
24
+ requests, one approving review, resolved conversations, current branches and
25
+ the `CI required`, CodeQL matrix and dependency-review checks. Select the
26
+ actual check names from GitHub. Block deletion and force pushes. Require code
27
+ owner review for changes; add another trusted maintainer so the sole owner's
28
+ pull requests can be reviewed. Do not silently bypass review to unblock them.
29
+ 4. Allow only reviewed Actions, keep the default workflow token read-only, and
30
+ disable Actions creating or approving pull requests. Keep fork approval on.
31
+ 5. Create environment `rubygems`, restrict deployment to `v*` tags, and configure a
32
+ trusted maintainer as required reviewer with self-review prevented. Confirm
33
+ an eligible second reviewer exists before enabling this requirement.
34
+ 6. Configure RubyGems trusted publishing exactly as [releasing](releasing.md)
35
+ specifies. Do not store a long-lived publishing key in repository secrets.
36
+
37
+ The authorized initial history consolidation is complete. Remote branch
38
+ `archive/pre-0.1.0-squash` preserves the old consumer pin. The `rubygems`
39
+ environment deploys only from `v*` tags (it allowed the default branch for the manual 0.1.0
40
+ release). RubyGems trusted publishing successfully published 0.1.0. A second reviewer remains a
41
+ separate repository setup task.
42
+ Never force-push just to make CI pass.
43
+
44
+ ## Release evidence
45
+
46
+ `CI required` fails if any Ruby test, package build, package installation or
47
+ audit fails or is skipped. Linux packages are built against glibc 2.28 and checked
48
+ for newer symbol requirements. Compatibility jobs install the same artifact,
49
+ not a newly rebuilt library.
50
+
51
+ The tag-triggered release workflow accepts only a successful CI run from this
52
+ repository, for the exact master commit the tag points to. It validates package names, versions, platforms and
53
+ license files before trusted publication, and records an attestation for the
54
+ promotion workflow. Keep the successful CI URL with release notes. GitHub
55
+ settings, hosted matrix success and RubyGems setup must be confirmed separately;
56
+ local tests do not establish any of them.
57
+
58
+ See GitHub's [secure Actions guidance](https://docs.github.com/en/actions/reference/security/secure-use)
59
+ and RubyGems' [trusted publishing guide](https://guides.rubygems.org/trusted-publishing/).
60
+
61
+ Rust scanning uses CodeQL’s supported `none` build mode with the pinned Rust
62
+ toolchain; see [GitHub’s Rust scanning requirements](https://docs.github.com/en/code-security/reference/code-scanning/codeql/build-options-for-compiled-languages#building-rust).
@@ -0,0 +1,45 @@
1
+ # Installing Forme Ruby
2
+
3
+ After reading this guide, you will know how installation differs between Git,
4
+ source and native packages, and how to check the installed renderer.
5
+
6
+ ## Requirements
7
+
8
+ CRuby 3.3 or later. Rails is optional.
9
+
10
+ | Package | Needs |
11
+ | --- | --- |
12
+ | `arm64-darwin` | macOS 15 or later on Apple Silicon. |
13
+ | `x86_64-linux-gnu` | Linux AMD64 with glibc 2.28 or later. |
14
+ | `aarch64-linux-gnu` | Linux ARM64 with glibc 2.28 or later. |
15
+ | `ruby` source gem or Git checkout | Rust/Cargo 1.94.0, a C linker, make and network access to the pinned Git and crates.io dependencies. |
16
+
17
+ Native gems need no compiler and no system Forme library.
18
+
19
+ ## Install from GitHub
20
+
21
+ Download the matching native gem and `SHA256SUMS` from the
22
+ [0.3.0 release](https://github.com/clearstackio/forme-ruby/releases/tag/v0.3.0).
23
+ Check its digest with `shasum -a 256 <filename>` against the checksum file, then
24
+ run `gem install ./<filename>`.
25
+
26
+ ## Install from RubyGems
27
+
28
+ Add to your Gemfile and run `bundle install`:
29
+
30
+ ```ruby
31
+ gem "forme-ruby", "~> 0.3.0", require: "forme_pdf"
32
+ ```
33
+
34
+ Bundler selects a matching native package where available and otherwise
35
+ installs the source gem, which needs the build tools above.
36
+
37
+ ## Verify the installation
38
+
39
+ ```bash
40
+ bundle exec ruby -rforme_pdf -e 'FormePDF.verify!; abort "Invalid PDF" unless FormePDF.render_html("<h1>Hello</h1>").start_with?("%PDF-")'
41
+ ```
42
+
43
+ `verify!` checks loading and ABI compatibility; the render exercises the engine.
44
+ For `FormePDF::LoadError`, check the installed platform and library permissions.
45
+ Reinstall the matching gem instead of copying a library from another platform.
data/docs/rails.md ADDED
@@ -0,0 +1,57 @@
1
+ # Rendering PDFs in Rails
2
+
3
+ After reading this guide, you will know how to render ERB to PDF while retaining
4
+ control of permissions, templates and HTTP responses. The core gem does not
5
+ require Rails; these examples assume an existing Rails application.
6
+
7
+ ## Render explicitly
8
+
9
+ Select and authorize records in your application's controller before rendering.
10
+ Supply a dedicated HTML template and layout:
11
+
12
+ ```ruby
13
+ html = render_to_string(template: "invoices/pdf", layout: "pdf", formats: [:html])
14
+ pdf = FormePDF.render_html(html)
15
+ send_data pdf, type: "application/pdf", disposition: "inline", filename: "invoice.pdf"
16
+ ```
17
+
18
+ Use `attachment` instead of `inline` when the application's download contract
19
+ requires it. Application code owns routes, record scopes, filenames, asset
20
+ selection and member-data masking. Keep browser print templates separate if
21
+ PDF styling needs different behavior.
22
+
23
+ ## Use the optional adapter
24
+
25
+ ```ruby
26
+ require "forme_pdf/rails"
27
+
28
+ class InvoicesController < ApplicationController
29
+ include FormePDF::Rails
30
+ end
31
+ ```
32
+
33
+ From an already authorized action:
34
+
35
+ ```ruby
36
+ pdf = render_forme_pdf(template: "invoices/pdf", layout: "pdf", locals: {invoice: @invoice})
37
+ send_data pdf, type: "application/pdf", disposition: "inline", filename: "invoice.pdf"
38
+ ```
39
+
40
+ `render_forme_pdf` returns bytes; it does not send a response. It passes
41
+ `formats: [:html]` to Rails and forwards rendering options to FormePDF. It does
42
+ not prepare assets, select records, install middleware, add routes or register
43
+ a Railtie. The host application supplies Rails and controls its lifecycle.
44
+
45
+ ## Verify at startup
46
+
47
+ Applications that require PDF availability can add this initializer:
48
+
49
+ ```ruby
50
+ FormePDF.verify!
51
+ ```
52
+
53
+ Load failure then prevents startup instead of silently disabling PDF reports.
54
+ Test actual rendering in the deployment image too. The adapter spec renders a
55
+ real `ActionController::Base` template and layout with Action Pack 8; consumers
56
+ must still test their actual Rails stack and report routes. No specific Rails
57
+ version matrix is claimed by this gem.
data/docs/releasing.md ADDED
@@ -0,0 +1,98 @@
1
+ # Preparing and Releasing Forme Ruby
2
+
3
+ After reading this guide, you will know how to qualify source/native artifacts
4
+ and which steps publish externally. **Published versions are listed in the [changelog](../CHANGELOG.md).**
5
+ Local preparation does not authorize a push, tag or RubyGems publication.
6
+
7
+ ## Prepare locally
8
+
9
+ 1. Review README, guides, AGENTS, CHANGELOG, gemspec metadata, LICENSE, NOTICE
10
+ and generated third-party notices. Keep public examples free of private data.
11
+ 2. Run the contributor checks and package-install checks. Inspect package files:
12
+ source gems contain the locked Rust sources/build hook; native gems contain
13
+ their library and no build hook. Confirm guides and all notices are included.
14
+ 3. Keep `lib/forme_pdf/version.rb` and CHANGELOG aligned. Do not date an unreleased
15
+ entry as if it were published. Review the tested Forme revision and platform
16
+ minimums whenever native dependencies change.
17
+ 4. If history is explicitly squashed, record old/new refs and keep a backup.
18
+ Previously successful CI does not qualify the new commit. Consumers must not
19
+ lock to an unpublished SHA. Do not change remote history during local preparation.
20
+
21
+ ## Qualify the release commit
22
+
23
+ After a separately authorized GitHub push, require successful `ci.yml` for that
24
+ exact `master` commit, including every package installation job. Review the four
25
+ intended artifacts: `ruby`, `arm64-darwin`, `x86_64-linux-gnu` and
26
+ `aarch64-linux-gnu`. The
27
+ [installation requirements](installation.md) must match what CI qualifies.
28
+
29
+ The initial history consolidation is complete. Branch `archive/pre-0.1.0-squash`
30
+ preserves the earlier history and existing consumer pin. Future releases should
31
+ use normal commits without rewriting published history.
32
+
33
+ Review [GitHub repository setup](github-setup.md) before enabling releases.
34
+
35
+ ## Configure trusted publishing
36
+
37
+ Under the `ajaya` RubyGems account, configure a pending publisher for the new gem:
38
+
39
+ | Field | Value |
40
+ | --- | --- |
41
+ | Gem | `forme-ruby` |
42
+ | GitHub owner | `clearstackio` |
43
+ | Repository | `forme-ruby` |
44
+ | Workflow | `release.yml` |
45
+ | Environment | `rubygems` |
46
+
47
+ Use the matching GitHub environment and review its protections. A pending
48
+ publisher becomes associated with the gem after its first successful upload.
49
+ See the [official RubyGems trusted publishing guide](https://guides.rubygems.org/trusted-publishing/)
50
+ for setup. No long-lived RubyGems API key is required by this workflow.
51
+
52
+ ## Publish only with explicit authorization
53
+
54
+ Pushing a `v*` tag publishes. `release.yml` runs on the tag and:
55
+
56
+ 1. checks the tag equals `v` plus `FormePDF::VERSION`;
57
+ 2. finds the successful `ci.yml` run on `master` for the tagged commit and
58
+ downloads its four packages, rebuilding nothing;
59
+ 3. validates names, versions, platforms, license files and build hooks;
60
+ 4. records a GitHub build-provenance attestation for those packages;
61
+ 5. creates the GitHub release with the packages and `SHA256SUMS`, or, when the
62
+ release already exists, requires its packages to match byte-for-byte;
63
+ 6. signs each package with Sigstore and pushes it to RubyGems through trusted
64
+ publishing with that attestation, then waits until RubyGems serves it.
65
+
66
+ This follows the RubyGems [trusted publishing release guide](https://guides.rubygems.org/trusted-publishing/releasing-gems/)
67
+ and our other gems:
68
+
69
+ 1. Update `VERSION` in `lib/forme_pdf/version.rb`.
70
+ 2. Move the Unreleased CHANGELOG entries under the new version and date.
71
+ 3. Commit to `master` and wait for CI to pass on that commit.
72
+ 4. Tag and push: `git tag vX.Y.Z && git push origin master vX.Y.Z`.
73
+
74
+ Treat the tag push as publication, not a dry run. Afterward, verify all four
75
+ packages and their attestations on RubyGems and install from RubyGems in a clean
76
+ environment. Partial publication cannot be overwritten: inspect which platforms
77
+ succeeded before deciding how to recover. Update consumer Gemfiles only after
78
+ the version is available and qualified.
79
+
80
+ ## Release evidence
81
+
82
+ [GitHub release 0.1.0](https://github.com/clearstackio/forme-ruby/releases/tag/v0.1.0)
83
+ contains the source gem, both native gems and SHA-256 checksums from
84
+ [CI run 35415089757](https://github.com/clearstackio/forme-ruby/actions/runs/35415089757).
85
+ Every job passed on commit `266628a20a0a52bad222c8f8e6d2277b08122896`, including
86
+ every package installation job. CodeQL also
87
+ passed. Packages were downloaded and validated before release; the macOS native
88
+ gem was additionally installed and rendered locally outside the checkout.
89
+
90
+ The GitHub `rubygems` environment exists.
91
+ [Registry publication run 35415885728](https://github.com/clearstackio/forme-ruby/actions/runs/35415885728)
92
+ succeeded through trusted publishing for all three platforms. Downloads from
93
+ RubyGems matched the CI and GitHub release artifacts byte-for-byte. A fresh
94
+ macOS ARM registry installation loaded the native library and rendered a PDF.
95
+
96
+ The publisher is configured; do not recreate it for subsequent versions.
97
+ A published version must never be pushed again. Use a new
98
+ version for future releases and qualify its packages before publication.
data/docs/rendering.md ADDED
@@ -0,0 +1,82 @@
1
+ # Rendering PDFs
2
+
3
+ After reading this guide, you will know how to render trusted HTML, register
4
+ fonts and inspect diagnostics. Install the gem before running these examples.
5
+
6
+ ## Render HTML
7
+
8
+ ```ruby
9
+ require "forme_pdf"
10
+
11
+ pdf = FormePDF.render_html("<h1>Invoice</h1>", css: "@page { size: Letter; margin: 0.75in; }")
12
+ File.binwrite("invoice.pdf", pdf)
13
+ ```
14
+
15
+ Input must be a String containing valid text. Valid non-UTF-8 encodings are
16
+ transcoded; binary input is interpreted as UTF-8. The result is a frozen binary
17
+ ASCII-8BIT String. Always write with `File.binwrite`.
18
+
19
+ ## Style pages and supply assets
20
+
21
+ Forme supports a subset of HTML and print CSS, not browser layout or JavaScript.
22
+ Use dedicated print styles and inspect the resulting pages. Inline CSS or pass
23
+ `css:`; embed images as data URIs. The binding does not fetch remote stylesheets,
24
+ fonts or images.
25
+
26
+ Image sources starting with `/`, `./` or `../` are files. They are omitted with a
27
+ warning unless you pass `image_root:`, a directory that must contain them:
28
+
29
+ ```ruby
30
+ pdf = FormePDF.render_html(
31
+ '<img src="./logo.png" width="120">',
32
+ image_root: Rails.root.join("app/assets/images")
33
+ )
34
+ ```
35
+
36
+ Relative paths resolve against `image_root`; absolute paths and symlinks must
37
+ resolve inside it. Each file must be a regular PNG, JPEG or WebP file of at most
38
+ 64 MiB. Warnings name the reason, never the path.
39
+
40
+ Supply TTF font bytes explicitly:
41
+
42
+ ```ruby
43
+ pdf = FormePDF.render_html(
44
+ '<p style="font-family: Report">A document</p>',
45
+ fonts: [{family: "Report", data: File.binread("report.ttf"), weight: 400, italic: false}]
46
+ )
47
+ ```
48
+
49
+ `css:`, `fonts:` and `image_root:` are the supported rendering keywords. Font
50
+ entries accept `family`, `data`, `weight` (an Integer from 1 to 1000, default
51
+ 400) and `italic` (true or false, default false). Unknown or invalid options
52
+ raise `ArgumentError`. Register the weights/styles your document needs and check the PDF.
53
+
54
+ ## Inspect diagnostics
55
+
56
+ ```ruby
57
+ result = FormePDF.render_html_result("<p>Report</p>")
58
+ File.binwrite("report.pdf", result.pdf)
59
+ puts result.passes
60
+ result.warnings.each { |warning| warn warning }
61
+ ```
62
+
63
+ The result and its warning array/strings are frozen. Unsupported CSS can produce
64
+ warnings without a failed render. Review warnings using synthetic input; do not
65
+ send sensitive document content or diagnostics to public logs.
66
+
67
+ ## Handle errors and concurrency
68
+
69
+ `FormePDF::LoadError` and `FormePDF::RenderError` inherit `FormePDF::Error`.
70
+ Invalid caller arguments, including text that is not valid UTF-8, raise
71
+ `ArgumentError`. Documents nested more than 512 elements deep raise
72
+ `FormePDF::RenderError` instead of rendering. Avoid
73
+ rescuing everything and returning an HTML success response as if it were a PDF.
74
+
75
+ Each render owns independent native result storage. Ruby copies the bytes and
76
+ frees that result even when copying or decoding fails. Native calls release the
77
+ Ruby lock and render on a native thread with its own 64 MiB stack, so deep
78
+ documents behave the same on Puma, Sidekiq and `Thread.new` threads as on the
79
+ main thread. Concurrent callers do not share output buffers. Ruby interruption is
80
+ masked during native ownership, so thread cancellation is not a render deadline.
81
+ Use process-level resource limits for large or hostile inputs. The API is not a
82
+ sandbox and exposes no per-render timeout.
@@ -0,0 +1,44 @@
1
+ # Reviewing Native Dependency Advisories
2
+
3
+ After reading this guide, you will understand the current audit exceptions and
4
+ when they must be reconsidered. Review date: 2026-10-20.
5
+
6
+ ## Scope
7
+
8
+ These exceptions acknowledge vulnerable dependencies; they do not patch them.
9
+ They apply only to Forme 0.28.0 revision `b97dc101b705ea5d7fea6fb1b20fabfb5bd2d63d`,
10
+ the locked dependency graph and the HTML-only Ruby API. Rendering is not a
11
+ sandbox for arbitrary HTML. See [SECURITY](../SECURITY.md).
12
+
13
+ | Advisory | Locked package | Why the affected path is inaccessible |
14
+ | --- | --- | --- |
15
+ | [RUSTSEC-2026-0195](https://rustsec.org/advisories/RUSTSEC-2026-0195.html) | quick-xml 0.37.5 | The engine uses plain `Reader`, never `NsReader` or its namespace resolver. |
16
+ | [RUSTSEC-2026-0194](https://rustsec.org/advisories/RUSTSEC-2026-0194.html) | quick-xml 0.37.5 | Duplicate-attribute handling is vulnerable in upstream SVG parsing, but the HTML mapper never constructs SVG nodes. |
17
+ | [RUSTSEC-2023-0071](https://rustsec.org/advisories/RUSTSEC-2023-0071.html) | rsa 0.9.10 | Private-key operations occur only in certification, which HTML conversion leaves disabled. |
18
+
19
+ ## Verify the boundaries
20
+
21
+ `ext/forme_pdf/src/lib.rs` accepts only CSS, fonts and an image root, rejects
22
+ unknown options, and reproduces `forme_pdf_html::render_html` with default HTML
23
+ options: `html_to_document`, then `forme::render_with_options`. Between the two
24
+ it replaces file image sources with data URIs or empties them, so the engine
25
+ never reads files itself; image bytes still reach only the image loader. In the pinned
26
+ upstream tree, `html/src/dom.rs` parses with html5ever. `html/src/map.rs` has no
27
+ `NodeKind::Svg` construction and initializes `certification: None`.
28
+ `engine/src/image_loader.rs` accepts JPEG, PNG and WebP, so an SVG image cannot
29
+ enter the XML parser through an image URL. Font registration does not parse XML.
30
+ Only `forme-pdf` consumes quick-xml and rsa in the locked dependency graph.
31
+
32
+ The exceptions are configured in `.cargo/audit.toml`. Scheduled CI continues to
33
+ report other advisories, including unmaintained dependency warnings. Re-review
34
+ all exceptions when the engine pin, options schema, Cargo features or exports
35
+ change, especially SVG, raw document/JSON, imports or signing. Check the exact
36
+ new call paths; do not carry exceptions forward automatically.
37
+
38
+ ## Remove exceptions when possible
39
+
40
+ Prefer an upstream update to quick-xml 0.41+ or feature-gating unused SVG and
41
+ certification dependencies. The current upstream 0.37 constraint prevents a
42
+ lockfile-only upgrade. RustSec lists no patched RSA version at review time;
43
+ a version bump alone is not remediation. Track upstream fixes during the weekly
44
+ dependency review and remove an exception once the dependency is fixed or removed.
data/examples/hello.rb ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "forme_pdf"
4
+
5
+ pdf = FormePDF.render_html("<h1>Hello from Ruby</h1>", css: "@page { size: Letter; }")
6
+ File.binwrite(ARGV.fetch(0, "hello.pdf"), pdf)
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FormePDF
4
+ class Error < StandardError; end
5
+ class RenderError < Error; end
6
+ class LoadError < Error; end
7
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+ module FormePDF
5
+ # Loads only a library supplied by this gem's build or package.
6
+ module Native
7
+ extend FFI::Library
8
+
9
+ @load_mutex = Mutex.new
10
+
11
+ # Load once and validate the versioned C ABI before use.
12
+ def self.load!
13
+ @load_mutex.synchronize do
14
+ return if @loaded
15
+ extension = FFI::Platform.mac? ? "dylib" : "so"
16
+ path = File.expand_path("native/libforme_pdf_native.#{extension}", __dir__)
17
+ fail FormePDF::LoadError, "Forme native library missing; reinstall forme-ruby for your platform (source installs require Rust/Cargo)" unless File.file?(path)
18
+ ffi_lib path
19
+ attach_function :forme_abi_version, [], :uint32
20
+ fail FormePDF::LoadError, "Incompatible Forme native ABI" unless forme_abi_version == 1
21
+ attach_function :forme_render_html, [:pointer, :size_t, :pointer, :size_t], :pointer, blocking: true
22
+ attach_function :forme_result_status, [:pointer], :int32
23
+ attach_function :forme_result_bytes, [:pointer, :uint32, :pointer], :pointer
24
+ attach_function :forme_result_destroy, [:pointer], :void
25
+ @loaded = true
26
+ end
27
+ rescue ::LoadError => e
28
+ fail FormePDF::LoadError, "Cannot load Forme native library: #{e.message}"
29
+ end
30
+
31
+ # Copy a borrowed native buffer before its owning result is destroyed.
32
+ def self.copy(result, field)
33
+ length = FFI::MemoryPointer.new(:size_t)
34
+ pointer = forme_result_bytes(result, field, length)
35
+ size = length.read(:size_t)
36
+ return "".b if size.zero?
37
+ fail FormePDF::RenderError, "Native result has a null buffer" if pointer.null?
38
+ pointer.read_string_length(size).b
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "forme_pdf"
4
+
5
+ module FormePDF
6
+ # Explicitly include this module in an ActionController; no Railtie or middleware.
7
+ module Rails
8
+ private
9
+
10
+ # Render a caller-selected Rails template into binary PDF bytes.
11
+ # The controller retains responsibility for authorization and send_data.
12
+ def render_forme_pdf(template:, layout:, locals: {}, **options)
13
+ html = render_to_string(template: template, layout: layout, locals: locals, formats: [:html])
14
+ FormePDF.render_html(html, **options)
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "base64"
5
+ module FormePDF
6
+ # One native render call with caller-owned input and independently owned output.
7
+ class Renderer
8
+ # Return PDF bytes, renderer warnings and layout pass count.
9
+ def self.call(html, css: nil, fonts: [], image_root: nil)
10
+ fail ArgumentError, "HTML must be a String" unless html.is_a?(String)
11
+ html = utf8(html, "HTML")
12
+ fail ArgumentError, "CSS must be a String or nil" unless css.nil? || css.is_a?(String)
13
+ fail ArgumentError, "fonts must be an Array" unless fonts.is_a?(Array)
14
+ options = JSON.generate(css: css && utf8(css, "CSS"), fonts: fonts.map { |font| font_option(font) }, image_root: image_root_option(image_root))
15
+ Native.load!
16
+ input = FFI::MemoryPointer.from_string(html)
17
+ opts = FFI::MemoryPointer.from_string(options)
18
+ # Async interruption must not arrive between native allocation and ownership.
19
+ Thread.handle_interrupt(Object => :never) do
20
+ result = Native.forme_render_html(input, html.bytesize, opts, options.bytesize)
21
+ fail RenderError, "Native renderer returned no result" if result.null?
22
+ if Native.forme_result_status(result) != 0
23
+ fail RenderError, Native.copy(result, 2).force_encoding(Encoding::UTF_8)
24
+ end
25
+ pdf = Native.copy(result, 0)
26
+ metadata = JSON.parse(Native.copy(result, 1))
27
+ Result.new(pdf: pdf.freeze, warnings: metadata.fetch("warnings").map(&:freeze).freeze, passes: metadata.fetch("passes"))
28
+ ensure
29
+ Native.forme_result_destroy(result) if result && !result.null?
30
+ end
31
+ end
32
+
33
+ # Binary text is read as UTF-8; other valid encodings are transcoded.
34
+ def self.utf8(text, name)
35
+ text = text.dup
36
+ text.force_encoding(Encoding::UTF_8) if text.encoding == Encoding::BINARY
37
+ fail ArgumentError, "#{name} must be valid UTF-8" unless text.valid_encoding?
38
+ text.encode(Encoding::UTF_8)
39
+ end
40
+
41
+ def self.font_option(font)
42
+ fail ArgumentError, "font must contain family and data" unless font.is_a?(Hash) && font[:family].is_a?(String) && font[:data].is_a?(String)
43
+ fail ArgumentError, "unknown font option" unless (font.keys - %i[family data weight italic]).empty?
44
+ weight = font.fetch(:weight, 400)
45
+ italic = font.fetch(:italic, false)
46
+ fail ArgumentError, "font weight must be an Integer from 1 to 1000" unless weight.is_a?(Integer) && weight.between?(1, 1000)
47
+ fail ArgumentError, "font italic must be true or false" unless [true, false].include?(italic)
48
+ {family: utf8(font[:family], "font family"), data: Base64.strict_encode64(font[:data]), weight: weight, italic: italic}
49
+ end
50
+
51
+ def self.image_root_option(root)
52
+ return if root.nil?
53
+ fail ArgumentError, "image_root must be a String or Pathname" unless root.is_a?(String) || root.respond_to?(:to_path)
54
+ root = File.expand_path(root.respond_to?(:to_path) ? root.to_path : root)
55
+ fail ArgumentError, "image_root must be an existing directory" unless File.directory?(root)
56
+ utf8(root, "image_root")
57
+ end
58
+ private_class_method :utf8, :font_option, :image_root_option
59
+ end
60
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FormePDF
4
+ Result = Data.define(:pdf, :warnings, :passes)
5
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FormePDF
4
+ VERSION = "0.3.0"
5
+ ENGINE_REVISION = "b97dc101b705ea5d7fea6fb1b20fabfb5bd2d63d"
6
+ end
data/lib/forme_pdf.rb ADDED
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "forme_pdf/version"
4
+ require_relative "forme_pdf/errors"
5
+ require_relative "forme_pdf/result"
6
+ require_relative "forme_pdf/native"
7
+ require_relative "forme_pdf/renderer"
8
+
9
+ module FormePDF
10
+ # Render HTML to a binary PDF String.
11
+ def self.render_html(html, **options)
12
+ render_html_result(html, **options).pdf
13
+ end
14
+
15
+ # Render HTML and preserve diagnostics.
16
+ def self.render_html_result(html, **options)
17
+ Renderer.call(html, **options)
18
+ end
19
+
20
+ # Validate the gem-owned native library eagerly, e.g. at application startup.
21
+ def self.verify!
22
+ Native.load!
23
+ true
24
+ end
25
+ end