htmlToPdf 3.0.1 → 4.0.0

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6f1fa8afa83a3397feb554c84966351b5a1c50557ab851c1f9e2d27e2228de6b
4
- data.tar.gz: 4e0bd81e53004c767dd542b247e3c5190f85ef64d03be7b0bdf18f4b5baedcec
3
+ metadata.gz: d0015b547aebfe40337ece556e2bf51a43a77b7d505e020bf536fe5d47381bd6
4
+ data.tar.gz: b698d9dcc31ced4e11e2bbee6c22210362271e587ae82c92eba1f12628b367d9
5
5
  SHA512:
6
- metadata.gz: 77a6d015867bcc6e2f9b4df1a2a060a335ea2fa1f7f66e0f63ce1431ecf4df6f55982f8ac77e7ff976a39160dab8732684bf277d4f3de5d525e1740b3f55cba6
7
- data.tar.gz: a37b215956bbf8cb06f9ba860246069d9dcf9c5ace999ec66834139599feec489c8f2a97a128f1f500ca5ac8198359b8d939eb031aba83319701703e0f82a370
6
+ metadata.gz: 86972fa6f518792daa579ed61cff3ef20b5c7863231f118816fb0c715acb70d5b2d05727ca5693c23ef401ae6e23feaceec96bab2a98d82d6d5be4a78bec3b74
7
+ data.tar.gz: 56abfcb83ff96c5de5845dfc052ffb99ac5629cbd3d26dcde0a072664e1d024df79c846395cfe01538d870c7b10cb3c8dd5201bae7cab171b37fb9cdc9305a46
data/.gitignore CHANGED
@@ -3,6 +3,7 @@
3
3
  /.bundle/
4
4
  /spec/internal/log/*.log
5
5
  /spec/internal/tmp/
6
+ /spec/internal/db/*.sqlite
6
7
  /tmp/
7
8
  .DS_Store
8
9
  .idea/
data/CHANGELOG.md CHANGED
@@ -3,6 +3,84 @@
3
3
  All notable changes to this project are documented here. Format loosely follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
+ ## [4.0.0] - 2026-11-24
7
+
8
+ The headline change: PDFs no longer have to be generated inline, in the request that asked for
9
+ them. `HtmlToPdf.generate_later` renders in the background via ActiveJob, tracks the job's status,
10
+ and can hand the finished PDF off to S3 or ActiveStorage instead of streaming it back — a big
11
+ enough expansion of what this gem does that it gets a major version bump, even though every
12
+ existing synchronous `include HtmlToPdf` / `around_action :html_to_pdf` integration keeps working
13
+ completely unchanged. **Nothing from 3.x needs to change to upgrade** — see "Upgrading from 3.x"
14
+ below.
15
+
16
+ ### Added: background rendering (`HtmlToPdf.generate_later`)
17
+
18
+ ```ruby
19
+ job = HtmlToPdf.generate_later(
20
+ controller: InvoicesController,
21
+ action: :show,
22
+ assigns: { invoice: invoice },
23
+ pdf_options: { title: "invoice", print_options: { format: "A4" } },
24
+ store: { adapter: :active_storage, record: invoice, attachment: :pdf },
25
+ metadata: { invoice_id: invoice.id }
26
+ )
27
+
28
+ HtmlToPdf::JobStatus.find(job.job_id) # => state/result/error/metadata
29
+ ```
30
+
31
+ - **`HtmlToPdf::GenerateJob`**, a plain `ActiveJob::Base` subclass built entirely on ActiveJob's own
32
+ public API (`retry_on`/`discard_on`/`queue_as`) — no Sidekiq- or Solid-Queue-specific code
33
+ anywhere, so it runs under whichever queue adapter the host app configures. Automatic retries on
34
+ the same transient Chrome errors `BrowserPool` already retries once internally; failed/discarded
35
+ jobs invoke the new `config.on_job_failure` callback. Required eagerly (guarded on
36
+ `ActiveJob::Base` already being defined) rather than lazily on first `generate_later` call —
37
+ found by actually running a background job against a real, separate Solid Queue worker process:
38
+ a worker that never itself calls `generate_later` still needs the job class defined in *its own*
39
+ process to perform a job the web process enqueued, and a lazy `require` inside `generate_later`
40
+ never runs there at all.
41
+ - **`HtmlToPdf::Renderer`**, the piece `generate_later` is built on — renders a controller action to
42
+ PDF bytes outside of a request, via `ActionController::Renderer` (the same mechanism ActionMailer
43
+ uses). Requires the new `config.default_url_options`, since there's no real request for it to
44
+ infer a host from — raises a clear `ArgumentError` if that's unset rather than silently rendering
45
+ broken asset/route URLs.
46
+ - **`HtmlToPdf::JobStatus`**, tracking a background job's `queued` → `processing` →
47
+ `completed`/`failed` lifecycle in `config.job_status_store` (default: a `Rails.cache`-backed
48
+ `CacheStore`, swappable for a custom store), so a different process than the one running the job
49
+ — e.g. the web process a user is polling from — can read it.
50
+ - **`HtmlToPdf::Storage`**, pluggable PDF storage with two adapters shipped:
51
+ - `:active_storage` — attaches to any ActiveRecord `has_one_attached`/`has_many_attached`, via
52
+ whatever service `config/storage.yml` already points at (disk, S3, GCS, ...).
53
+ - `:s3` — direct upload via `aws-sdk-s3`, for apps that don't use ActiveStorage and just want a
54
+ plain bucket/key/URL back. **A true optional dependency — this gem does not depend on
55
+ `aws-sdk-s3`**; add it to your own Gemfile to use `:s3`.
56
+ - Register your own with `HtmlToPdf::Storage.register(:name, AdapterClass)`.
57
+ - **`config.max_concurrent_renders`** (default `nil`, unbounded — unchanged behavior) — caps how
58
+ many conversions may run against the shared `BrowserPool` browser at once, via the new
59
+ `HtmlToPdf::ConcurrencyLimiter`. Applies to the synchronous controller path too, not just jobs,
60
+ since both funnel through the same one Chrome process per Ruby process.
61
+ - New config: `config.job_status_store`, `config.job_status_ttl`, `config.job_queue_name`,
62
+ `config.on_job_success`, `config.on_job_failure`, `config.default_url_options`,
63
+ `config.s3_bucket`, `config.s3_client_options`.
64
+
65
+ ### Changed (internal, non-breaking)
66
+
67
+ - Extracted the "write HTML to a temp file, convert via `BrowserPool`, clean up" logic (previously
68
+ inlined in `html_to_pdf`) into `HtmlToPdf::Converter`, shared by both the synchronous controller
69
+ path and `HtmlToPdf::Renderer` — no behavior change to the synchronous path, just one copy of the
70
+ logic instead of two.
71
+
72
+ ### Upgrading from 3.x
73
+
74
+ Nothing to do. Every new piece is additive, defaults to today's exact behavior (unbounded
75
+ concurrency, no background store, etc.), and the synchronous path's code, options, and security
76
+ model (see [Security](docs/security.md)) are untouched. Adopt `HtmlToPdf.generate_later` wherever
77
+ and whenever it's useful — the two paths compose freely in the same app.
78
+
79
+ See [Background PDF generation](docs/background-jobs.md) for the full write-up, including why
80
+ retry `attempts`/`wait` are fixed rather than a `HtmlToPdf.configure` option (a class-definition-
81
+ time-vs-initializer-load-order hazard, explained there), the cross-process cache-visibility caveat
82
+ for job status in production, and a detailed look at each storage adapter.
83
+
6
84
  ## [3.0.1] - 2026-11-24
7
85
 
8
86
  - **Security: patched a batch of transitive dependency CVEs** flagged by GitHub's dependency
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- htmlToPdf (3.0.1)
4
+ htmlToPdf (4.0.0)
5
5
  activesupport (>= 7.0, < 9)
6
6
  ferrum (>= 0.13, < 1.0)
7
7
 
@@ -84,6 +84,26 @@ GEM
84
84
  uri (>= 0.13.1)
85
85
  addressable (2.10.0)
86
86
  public_suffix (>= 2.0.2, < 8.0)
87
+ aws-eventstream (1.4.1)
88
+ aws-partitions (1.1311.0)
89
+ aws-sdk-core (3.272.0)
90
+ aws-eventstream (~> 1, >= 1.4.1)
91
+ aws-partitions (~> 1, >= 1.992.0)
92
+ aws-sigv4 (~> 1.9)
93
+ base64
94
+ bigdecimal
95
+ jmespath (~> 1, >= 1.6.1)
96
+ logger
97
+ rexml (~> 3.4, >= 3.4.2)
98
+ aws-sdk-kms (1.145.0)
99
+ aws-sdk-core (~> 3, >= 3.270.0)
100
+ aws-sigv4 (~> 1.5)
101
+ aws-sdk-s3 (1.245.2)
102
+ aws-sdk-core (~> 3, >= 3.269.0)
103
+ aws-sdk-kms (~> 1)
104
+ aws-sigv4 (~> 1.5)
105
+ aws-sigv4 (1.12.1)
106
+ aws-eventstream (~> 1, >= 1.0.2)
87
107
  base64 (0.3.0)
88
108
  bigdecimal (4.1.3)
89
109
  builder (3.3.0)
@@ -117,6 +137,7 @@ GEM
117
137
  prism (>= 1.3.0)
118
138
  rdoc (>= 4.0.0)
119
139
  reline (>= 0.4.2)
140
+ jmespath (1.6.2)
120
141
  json (3.0.2)
121
142
  logger (1.7.0)
122
143
  loofah (2.25.3)
@@ -201,6 +222,7 @@ GEM
201
222
  tsort
202
223
  reline (0.7.0)
203
224
  io-console (~> 0.5)
225
+ rexml (3.4.4)
204
226
  rspec (3.13.2)
205
227
  rspec-core (~> 3.13.0)
206
228
  rspec-expectations (~> 3.13.0)
@@ -223,6 +245,7 @@ GEM
223
245
  rspec-support (~> 3.13)
224
246
  rspec-support (3.13.7)
225
247
  securerandom (0.4.1)
248
+ sqlite3 (2.10.2-arm64-darwin)
226
249
  thor (1.5.0)
227
250
  timeout (0.6.1)
228
251
  tsort (0.2.0)
@@ -240,6 +263,7 @@ PLATFORMS
240
263
  arm64-darwin-25
241
264
 
242
265
  DEPENDENCIES
266
+ aws-sdk-s3 (~> 1.0)
243
267
  bundler (>= 2.4, < 5)
244
268
  bundler-audit (~> 0.9)
245
269
  combustion (~> 1.5)
@@ -248,6 +272,7 @@ DEPENDENCIES
248
272
  rake (>= 13.0, < 14)
249
273
  rspec (~> 3.13)
250
274
  rspec-rails (~> 7.0)
275
+ sqlite3 (~> 2.0)
251
276
 
252
277
  CHECKSUMS
253
278
  action_text-trix (2.1.19) sha256=7012f59421009cf284aa651294896414d653a61a2417c9b8714c8476d2f74009
@@ -263,6 +288,12 @@ CHECKSUMS
263
288
  activestorage (8.1.4.1) sha256=0f4e2f114f3584723a80a2c089aacc6170e765a0b2c385c9782e26ed78f05c66
264
289
  activesupport (8.1.4.1) sha256=16ac4f341ca65c85a1fcdb8ac73f68891aae9e3c4a6f9c3a27daed8b00017ed7
265
290
  addressable (2.10.0) sha256=5e13b9c001adf01dd65ad6e0d2a91d2bc07885c0ff2b83f48cbcd95e08d9de62
291
+ aws-eventstream (1.4.1) sha256=ceb6a99c61df4bb00344e54aed0351574beca24f87a0d1487d1d2ed80929ce96
292
+ aws-partitions (1.1311.0) sha256=de5d8bb04d3f184317e7c02bbf1ee4ee5f5095fe1461b8fbd618ebba607a6f93
293
+ aws-sdk-core (3.272.0) sha256=decc1b6385865ea0756bb3d5926e7cef4628d8ec2b76d6748fd71df50997590d
294
+ aws-sdk-kms (1.145.0) sha256=ddbe86fca434f9a28bd0480b68fc0ce8bae555b6fd41b370bb00caa2dcf58853
295
+ aws-sdk-s3 (1.245.2) sha256=df02d9a5d969728c8c6f3b48e783646a839215dca6c5242cea45eb14144fad7a
296
+ aws-sigv4 (1.12.1) sha256=6973ff95cb0fd0dc58ba26e90e9510a2219525d07620c8babeb70ef831826c00
266
297
  base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b
267
298
  bigdecimal (4.1.3) sha256=61ebe1e5e559bdc3cc6f2c0ee7f427321fc838f59611c294356eb04d6e21cf66
268
299
  builder (3.3.0) sha256=497918d2f9dca528fdca4b88d84e4ef4387256d984b8154e9d5d3fe5a9c8835f
@@ -278,10 +309,11 @@ CHECKSUMS
278
309
  erubi (1.13.1) sha256=a082103b0885dbc5ecf1172fede897f9ebdb745a4b97a5e8dc63953db1ee4ad9
279
310
  ferrum (0.18.0) sha256=4cb8be16e352fc1d75f087e9214b34ec1b93ba932410c730a4724909ca89d7c6
280
311
  globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427
281
- htmlToPdf (3.0.1)
312
+ htmlToPdf (4.0.0)
282
313
  i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5
283
314
  io-console (0.9.4) sha256=a403304f32928ee85e56d457b4612ca43f2703b561a3258844992bd24085fbb1
284
315
  irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3
316
+ jmespath (1.6.2) sha256=238d774a58723d6c090494c8879b5e9918c19485f7e840f2c1c7532cf84ebcb1
285
317
  json (3.0.2) sha256=8e6d7e7b11384c21230430cef90b71f14849a34a1f4452796670f7c981bd19df
286
318
  logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
287
319
  loofah (2.25.3) sha256=545f14eef0cc2a7de80df560530d593232b7c07e515c5c4e37532d9cb5b0185c
@@ -312,6 +344,7 @@ CHECKSUMS
312
344
  rbs (4.2.0) sha256=51f7b886dcc05bc09e10b901daa6a81829f6adc03101d6ca9ea4aac6103e0674
313
345
  rdoc (8.1.0) sha256=befc37880a5cfd36dcb176c748b5fd5ee39dd3536a75e81824e4972ce230f60a
314
346
  reline (0.7.0) sha256=5b012d8e55dbf9d450f12bde2cf7d15ff546ae80b3f8f3b30e570d431815583d
347
+ rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142
315
348
  rspec (3.13.2) sha256=206284a08ad798e61f86d7ca3e376718d52c0bc944626b2349266f239f820587
316
349
  rspec-core (3.13.6) sha256=a8823c6411667b60a8bca135364351dda34cd55e44ff94c4be4633b37d828b2d
317
350
  rspec-expectations (3.13.5) sha256=33a4d3a1d95060aea4c94e9f237030a8f9eae5615e9bd85718fe3a09e4b58836
@@ -319,6 +352,7 @@ CHECKSUMS
319
352
  rspec-rails (7.1.1) sha256=e15dccabed211e2fd92f21330c819adcbeb1591c1d66c580d8f2d8288557e331
320
353
  rspec-support (3.13.7) sha256=0640e5570872aafefd79867901deeeeb40b0c9875a36b983d85f54fb7381c47c
321
354
  securerandom (0.4.1) sha256=cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1
355
+ sqlite3 (2.10.2-arm64-darwin) sha256=5b0d235ea037e6dcd1b8387a19d73be571917db9f93044d35741cf933a21a37d
322
356
  thor (1.5.0) sha256=e3a9e55fe857e44859ce104a84675ab6e8cd59c650a49106a05f55f136425e73
323
357
  timeout (0.6.1) sha256=78f57368a7e7bbadec56971f78a3f5ecbcfb59b7fcbb0a3ed6ddc08a5094accb
324
358
  tsort (0.2.0) sha256=9650a793f6859a43b6641671278f79cfead60ac714148aabe4e3f0060480089f
data/README.md CHANGED
@@ -6,7 +6,9 @@
6
6
 
7
7
  Turn any Rails controller action into a downloadable PDF, rendered exactly as the browser would
8
8
  render it — real CSS, real layout, real fonts — via a pooled headless Chrome instance instead of
9
- an abandoned wkhtmltopdf binary.
9
+ an abandoned wkhtmltopdf binary. Generate it inline in the request, or hand it off to a background
10
+ job (ActiveJob — Sidekiq, Solid Queue, or any adapter) with job status tracking and S3/ActiveStorage
11
+ storage — see [Background rendering](#background-rendering) below.
10
12
 
11
13
  Supports Rails 7.x and Rails 8.x (latest).
12
14
 
@@ -19,6 +21,8 @@ Renders through a pooled headless Chrome instance (via the [ferrum](https://gith
19
21
  - [HtmlToPdf in Rails](docs/rails-integration.md) — callback ordering, custom layouts, Chrome in
20
22
  Docker, and the `asset_host` gotcha that leaves a PDF unstyled if you miss it.
21
23
  - [Security](docs/security.md) — exactly what's safe to expose on a public action and what isn't.
24
+ - [Background PDF generation](docs/background-jobs.md) — `HtmlToPdf.generate_later`, ActiveJob/
25
+ Sidekiq/Solid Queue, retries, job status tracking, and S3/ActiveStorage storage.
22
26
  - [Contributing & Releasing](docs/contributing.md) — running the test suite, extending the gem.
23
27
  - Longer-form guides on the [docs site](https://ramlaxmanyadav.github.io/htmlToPdf/):
24
28
  - [Headless Chrome vs. wkhtmltopdf for Rails PDF generation](https://ramlaxmanyadav.github.io/htmlToPdf/headless-chrome-vs-wkhtmltopdf.html)
@@ -102,6 +106,25 @@ customizing page padding and print options:
102
106
 
103
107
  ##### Security note: `pdf_options` is read from the request's query params. `print_options` is a fixed, narrow set of PDF layout flags (margins, paper size, etc.) rather than arbitrary CLI arguments forwarded to a subprocess, so it can't be used to inject arbitrary binary flags — `header_template`/`footer_template` are the one exception (raw HTML Chrome renders as-is) and are filtered out of request-supplied options by default. Still, only expose the pdf format on actions where letting a caller tweak layout/margins is acceptable, or filter `pdf_options` yourself before it reaches `html_to_pdf` (e.g. in a `before_action` that runs earlier). Full detail in [Security](docs/security.md).
104
108
 
109
+ ## Background rendering
110
+
111
+ For PDFs slow enough that a caller shouldn't hold a connection open for them, or that should end
112
+ up in storage rather than streamed back directly, `HtmlToPdf.generate_later` enqueues an ActiveJob
113
+ job (Sidekiq/Solid Queue compatible, automatic retries, job status tracking, S3/ActiveStorage
114
+ storage, configurable concurrency, failure callbacks):
115
+
116
+ HtmlToPdf.generate_later(
117
+ controller: InvoicesController,
118
+ action: :show,
119
+ assigns: { invoice: invoice },
120
+ pdf_options: { title: 'invoice', print_options: { format: 'A4' } },
121
+ store: { adapter: :active_storage, record: invoice, attachment: :pdf }
122
+ )
123
+
124
+ See [Background PDF generation](docs/background-jobs.md) for the required one-time setup
125
+ (`config.default_url_options`), the full `HtmlToPdf::JobStatus`/`HtmlToPdf::Storage` API, and how
126
+ retries/concurrency/failure callbacks work.
127
+
105
128
  ## Configuration
106
129
 
107
130
  Set gem-wide defaults in an initializer (e.g. `config/initializers/html_to_pdf.rb`):
@@ -146,6 +169,28 @@ Set gem-wide defaults in an initializer (e.g. `config/initializers/html_to_pdf.r
146
169
  # caller can't stall the shared browser pool for everyone. Defaults
147
170
  # to 10_000.
148
171
  # config.max_javascript_delay_ms = 10_000
172
+
173
+ # Required to use HtmlToPdf.generate_later (background rendering) —
174
+ # there's no request to infer a host from in a job. These are
175
+ # ActionController::Renderer's env keys (http_host/https), not
176
+ # config.action_mailer.default_url_options's (host/protocol). See
177
+ # docs/background-jobs.md.
178
+ # config.default_url_options = { http_host: "app.example.com", https: true }
179
+
180
+ # Caps how many conversions may run against the shared browser at
181
+ # once (nil, the default, means unbounded). See docs/background-jobs.md.
182
+ # config.max_concurrent_renders = 10
183
+
184
+ # Defaults consumed by HtmlToPdf::Storage::S3Adapter. Leave
185
+ # credentials out and let the AWS SDK's default credential chain (an
186
+ # instance/task IAM role) resolve them.
187
+ # config.s3_bucket = "my-bucket"
188
+ # config.s3_client_options = { region: "us-east-1" }
189
+
190
+ # Called after a background job completes/fails for good. See
191
+ # docs/background-jobs.md.
192
+ # config.on_job_success = ->(status) { ... }
193
+ # config.on_job_failure = ->(status, error) { ... }
149
194
  end
150
195
 
151
196
  A single headless Chrome process is started lazily and reused across requests in the same Ruby process (each conversion gets its own isolated browser context), since launching Chrome per-request is comparatively expensive. It's restarted automatically if Chrome crashes or stops responding. See [Architecture](docs/architecture.md#browserpool) for the design and its scaling limits.
@@ -0,0 +1,229 @@
1
+ # Background PDF generation
2
+
3
+ [← Back to README](../README.md)
4
+
5
+ `HtmlToPdf.generate_later` is the async counterpart to the synchronous `include HtmlToPdf` /
6
+ `around_action :html_to_pdf` path: instead of streaming the PDF back in the response, it enqueues
7
+ an ActiveJob job that renders the view, converts it, optionally stores it (S3/ActiveStorage), and
8
+ tracks its own status so a different process (e.g. your web process, checking on a Sidekiq/Solid
9
+ Queue worker) can poll it.
10
+
11
+ ## Quick start
12
+
13
+ ```ruby
14
+ job = HtmlToPdf.generate_later(
15
+ controller: InvoicesController,
16
+ action: :show,
17
+ assigns: { invoice: invoice }, # ivars the view needs
18
+ pdf_options: { title: "invoice", print_options: { format: "A4" } },
19
+ store: { adapter: :active_storage, record: invoice, attachment: :pdf },
20
+ metadata: { invoice_id: invoice.id }
21
+ )
22
+
23
+ job.job_id # => a String you can hang onto (e.g. render it to the client to poll with)
24
+
25
+ HtmlToPdf::JobStatus.find(job.job_id)
26
+ # => #<HtmlToPdf::JobStatus state: "completed", result: {...}, metadata: {invoice_id: 1}, ...>
27
+ ```
28
+
29
+ Required one-time setup, in an initializer:
30
+
31
+ ```ruby
32
+ HtmlToPdf.configure do |config|
33
+ # There's no real request in a background job for HtmlToPdf::Renderer to
34
+ # infer a host from — this is required, and HtmlToPdf.generate_later
35
+ # raises a clear ArgumentError if it's missing. Note these are
36
+ # ActionController::Renderer's env keys (http_host/https), not
37
+ # config.action_mailer.default_url_options's (host/protocol).
38
+ config.default_url_options = { http_host: "app.example.com", https: true }
39
+ end
40
+ ```
41
+
42
+ ## How it renders without a request
43
+
44
+ `HtmlToPdf::Renderer` uses [`ActionController::Renderer`](https://api.rubyonrails.org/classes/ActionController/Renderer.html)
45
+ — the same mechanism ActionMailer itself uses to render views outside of a request — rather than
46
+ a real controller instance's `render_to_string`. The actual HTML-to-PDF conversion
47
+ (`HtmlToPdf::Converter`) is the exact same code the synchronous path uses: write to a temp file,
48
+ point headless Chrome at it via `file://`, convert, clean up. `print_options`/`header_template`
49
+ filtering goes through the same `HtmlToPdf::PrintOptions` as the synchronous path too — see
50
+ [Security](security.md) for what that means for a job's `pdf_options`.
51
+
52
+ **The `asset_host` gotcha is worse here than in a real request** (see
53
+ [Rails integration](rails-integration.md#the-asset_host-gotcha)): there's no `request` object at
54
+ all for a `Proc`-based `config.action_controller.asset_host` to close over. If your views load any
55
+ asset (CSS, images), `asset_host` needs to be a plain string/host, not the request-derived `Proc`
56
+ form, when rendering from a job.
57
+
58
+ `assigns:` — not `params:` — is the actual mechanism for feeding a view data here (`params:` isn't
59
+ a thing `ActionController::Renderer#render` accepts; it just forwards straight to
60
+ `render_to_string`). ActiveRecord objects pass through `assigns:` fine, since ActiveJob serializes
61
+ them via GlobalID.
62
+
63
+ ## Sidekiq / Solid Queue "compatibility"
64
+
65
+ `HtmlToPdf::GenerateJob` is a plain `ActiveJob::Base` subclass using only `retry_on`/`discard_on`/
66
+ `queue_as` — ActiveJob's own public API, nothing Sidekiq- or Solid-Queue-specific anywhere. It runs
67
+ under whichever adapter your app configures via `config.active_job.queue_adapter`. "Compatible with
68
+ Sidekiq and Solid Queue" is true by construction here, not something this gem's own CI spins up
69
+ both backends to verify (its specs run against ActiveJob's built-in `:test` adapter).
70
+
71
+ ### Setting up Solid Queue
72
+
73
+ Rails 8's default. `config/environments/production.rb` (or any environment you want it in):
74
+
75
+ ```ruby
76
+ config.active_job.queue_adapter = :solid_queue
77
+ ```
78
+
79
+ Run a worker as its own process alongside your web server:
80
+
81
+ ```
82
+ bin/jobs
83
+ ```
84
+
85
+ **The web process and the worker process are separate Ruby processes with separate memory** — see
86
+ "Job status tracking" below for why that means `config.cache_store` needs to be something other
87
+ than `:memory_store` for `HtmlToPdf::JobStatus` to actually be readable from the web side.
88
+
89
+ ### Setting up Sidekiq
90
+
91
+ Add it to your Gemfile (this gem does not depend on it — same "bring your own adapter" stance as
92
+ `aws-sdk-s3`):
93
+
94
+ ```ruby
95
+ gem "sidekiq"
96
+ ```
97
+
98
+ ```ruby
99
+ # config/initializers/sidekiq.rb
100
+ Sidekiq.configure_server { |c| c.redis = { url: ENV.fetch("REDIS_URL") } }
101
+ Sidekiq.configure_client { |c| c.redis = { url: ENV.fetch("REDIS_URL") } }
102
+ ```
103
+
104
+ ```ruby
105
+ # config/environments/production.rb
106
+ config.active_job.queue_adapter = :sidekiq
107
+ ```
108
+
109
+ Run a worker:
110
+
111
+ ```
112
+ bundle exec sidekiq
113
+ ```
114
+
115
+ Same caveat as Solid Queue: the worker is a separate process from your web server, so
116
+ `config.cache_store` needs to be Redis (or another shared store) — not `:memory_store` — for job
117
+ status to be visible from the web side. If you're already running Redis for Sidekiq, pointing
118
+ `config.cache_store` at the same Redis instance (`:redis_cache_store`) is the path of least
119
+ resistance.
120
+
121
+ ### Any other ActiveJob adapter
122
+
123
+ The same applies to anything else ActiveJob supports (`good_job`, `que`, `delayed_job`, ...) —
124
+ there's nothing in this gem to configure beyond `config.active_job.queue_adapter` itself and,
125
+ again, a cache store that isn't tied to one process.
126
+
127
+ ## Retries and failures
128
+
129
+ `GenerateJob` retries the same errors `BrowserPool` itself retries once internally (a crashed/
130
+ unresponsive Chrome — `Ferrum::DeadBrowserError`, `ProcessTimeoutError`, `TimeoutError`,
131
+ `NoSuchPageError`), up to 3 job-level attempts, with `wait: :polynomially_longer`. A bad
132
+ `print_options` value (`ArgumentError`) is discarded immediately instead — retrying a validation
133
+ error can't fix it.
134
+
135
+ **Retry `attempts`/`wait` are fixed, not a `HtmlToPdf.configure` option — on purpose.** `retry_on`
136
+ is a class-level macro evaluated once when this gem is `require`d, which happens at
137
+ `Bundler.require` time — *before* your own `config/initializers/html_to_pdf.rb` has run. A config
138
+ value read at that point would always see this gem's default, never your override, which would be
139
+ a confusing, silent footgun. If you want different retry/discard/queue semantics, define your own
140
+ tiny `ActiveJob::Base` subclass on the same primitives `GenerateJob` itself is built from:
141
+
142
+ ```ruby
143
+ class MyPdfJob < ActiveJob::Base
144
+ retry_on Ferrum::DeadBrowserError, wait: 10.seconds, attempts: 10
145
+
146
+ def perform(...)
147
+ pdf_bytes = HtmlToPdf::Renderer.render(...)
148
+ HtmlToPdf::Storage.store(pdf_bytes, adapter: :s3, key: ...)
149
+ end
150
+ end
151
+ ```
152
+
153
+ (`config.job_queue_name` *is* a safe runtime option — `queue_as { HtmlToPdf.configuration.job_queue_name }`
154
+ uses ActiveJob's block form, which is evaluated per-enqueue, not at class-definition time.)
155
+
156
+ `config.on_job_success` / `config.on_job_failure` are optional Procs called with the
157
+ `HtmlToPdf::JobStatus` (and the exception, for `on_job_failure`) once a job finishes — for good, in
158
+ the failure case, i.e. after retries are exhausted or the job was discarded.
159
+
160
+ ## Job status tracking
161
+
162
+ `HtmlToPdf::JobStatus` persists each job's `queued` → `processing` → `completed`/`failed`
163
+ transitions to `config.job_status_store`, which defaults to `HtmlToPdf::JobStatus::CacheStore` — a
164
+ thin wrapper over `Rails.cache`, namespaced under `htmlToPdf:job_status:<job_id>`, with
165
+ `config.job_status_ttl` (default 24 hours) as the expiry.
166
+
167
+ **This needs a shared cache store in production to actually be visible across processes.**
168
+ `Rails.cache`'s `:memory_store`/`:file_store` are per-process — a web process will never see a
169
+ status a *different* Sidekiq/Solid Queue worker process wrote with either of those. Configure
170
+ Redis, Solid Cache, or Memcached for `config.cache_store` if you're polling job status from a
171
+ different process than the one running the job (the normal case).
172
+
173
+ Swap the store entirely with any object responding to `#read(job_id)` / `#write(job_id, attrs)`:
174
+
175
+ ```ruby
176
+ config.job_status_store = MyActiveRecordBackedStore.new
177
+ ```
178
+
179
+ ## Storage adapters
180
+
181
+ `HtmlToPdf::Storage.store(pdf_bytes, adapter:, **options)` dispatches to a registered adapter.
182
+ Two ship with the gem:
183
+
184
+ - **`:active_storage`** (`HtmlToPdf::Storage::ActiveStorageAdapter`) — attaches the PDF to an
185
+ ActiveRecord record via `has_one_attached`/`has_many_attached`, using whatever service
186
+ `config/storage.yml` already points your app at (disk, S3, GCS, ...).
187
+ `{ adapter: :active_storage, record:, attachment:, filename: "document.pdf" }`.
188
+ - **`:s3`** (`HtmlToPdf::Storage::S3Adapter`) — direct upload via `aws-sdk-s3`, for apps that don't
189
+ use ActiveStorage and just want a plain bucket/key/URL back, no blob/attachment bookkeeping.
190
+ `{ adapter: :s3, key:, bucket: (or config.s3_bucket) }`. **htmlToPdf does not depend on
191
+ `aws-sdk-s3`** — add it to your own Gemfile to use this adapter. Prefer leaving credentials out
192
+ of `config.s3_client_options` and letting the AWS SDK's default credential chain (an EC2/ECS
193
+ instance role) resolve them; only pass explicit credentials if an instance role genuinely isn't
194
+ an option (e.g. a cross-account bucket).
195
+
196
+ Register your own with `HtmlToPdf::Storage.register(:my_adapter, MyAdapterClass)` — any class
197
+ whose `#initialize` takes the call's `**options` and whose `#store(pdf_bytes)` returns a plain,
198
+ cache-serializable Hash (that return value becomes `JobStatus#result`).
199
+
200
+ ## Troubleshooting
201
+
202
+ - **A job sits in `"queued"` forever.** No worker process is running against that queue, or
203
+ `config.job_queue_name` doesn't match what the worker is listening to (Solid Queue's
204
+ `config/queue.yml` `queues: "*"` listens to everything by default; Sidekiq needs the queue name
205
+ in its own `-q`/`:queues` config). Confirm a worker process (`bin/jobs`, `bundle exec sidekiq`,
206
+ ...) is actually running, separately from the web server.
207
+ - **`HtmlToPdf::JobStatus.find` returns a status with a `nil` state even though the job clearly
208
+ ran** (you can see it in the worker's log). `config.cache_store` is `:memory_store` or
209
+ `:file_store` in the process you're reading from, and the write happened in a *different*
210
+ process — see "Job status tracking" above. This is the single most common setup mistake.
211
+ - **`HtmlToPdf::Storage::ActiveStorageAdapter` raises `LoadError: ActiveStorage isn't loaded`.**
212
+ The app was generated with `--skip-active-storage` (or `Rails.application.config.active_storage`
213
+ was never configured). Either undo that, or use `:s3` instead.
214
+ - **`HtmlToPdf::Storage::S3Adapter` raises `ArgumentError: ... needs a bucket`.** Pass `bucket:` on
215
+ the call, or set `config.s3_bucket` — one of the two is required, there's no implicit default.
216
+ - **A job fails immediately with `ActiveJob::DeserializationError` mentioning a controller or
217
+ record.** Something passed to `assigns:`/`store:` (via GlobalID) was deleted before the job ran.
218
+ This is the same failure mode any ActiveJob job has when it's handed a record that disappears
219
+ before it executes — not specific to this gem.
220
+
221
+ ## Concurrency
222
+
223
+ `config.max_concurrent_renders` (default `nil`, unbounded — today's exact behavior) caps how many
224
+ conversions may run against the shared `BrowserPool` browser at once, via
225
+ `HtmlToPdf::ConcurrencyLimiter`. Applies to the synchronous controller path too, not just jobs,
226
+ since both funnel through the same one Chrome process per Ruby process — see
227
+ [Architecture](architecture.md#browserpool)'s scaling note. A web app under normal load rarely
228
+ needs this; a Sidekiq/Solid Queue pool with many worker threads all calling
229
+ `HtmlToPdf.generate_later` at once is the case it exists for.
data/htmlToPdf.gemspec CHANGED
@@ -8,8 +8,8 @@ Gem::Specification.new do |spec|
8
8
  spec.version = HtmlToPdf::VERSION
9
9
  spec.authors = ["Ram Laxman Yadav"]
10
10
  spec.email = ["yadavramlaxman@gmail.com"]
11
- spec.summary = %q{Render Rails controller actions to PDF using headless Chrome}
12
- spec.description = %q{HtmlToPdf lets any Rails controller action be downloaded as a PDF. Request the action with a PDF format and the gem renders the view exactly as the browser would, then converts it to PDF via a pooled headless Chrome instance (through the ferrum gem). Supports Rails 7.x and 8.x.}
11
+ spec.summary = %q{Render Rails controller actions to PDF, synchronously or in the background, using headless Chrome}
12
+ spec.description = %q{HtmlToPdf lets any Rails controller action be downloaded as a PDF. Request the action with a PDF format and the gem renders the view exactly as the browser would, then converts it to PDF via a pooled headless Chrome instance (through the ferrum gem) — synchronously, in-request, or in the background via HtmlToPdf.generate_later (ActiveJob, so it runs under Sidekiq/Solid Queue/any adapter), with job status tracking and S3/ActiveStorage storage. Supports Rails 7.x and 8.x.}
13
13
  spec.homepage = "https://github.com/ramlaxmanyadav/htmlToPdf"
14
14
  spec.license = "MIT"
15
15
  spec.required_ruby_version = ">= 3.1"
@@ -33,4 +33,6 @@ Gem::Specification.new do |spec|
33
33
  spec.add_development_dependency "combustion", "~> 1.5"
34
34
  spec.add_development_dependency "rails", ">= 7.0", "< 9"
35
35
  spec.add_development_dependency "bundler-audit", "~> 0.9"
36
+ spec.add_development_dependency "aws-sdk-s3", "~> 1.0"
37
+ spec.add_development_dependency "sqlite3", "~> 2.0"
36
38
  end
@@ -1,4 +1,5 @@
1
1
  require "ferrum"
2
+ require "htmlToPdf/concurrency_limiter"
2
3
 
3
4
  module HtmlToPdf
4
5
  # Keeps a single headless Chrome process alive per Ruby process (starting
@@ -19,18 +20,20 @@ module HtmlToPdf
19
20
  module_function
20
21
 
21
22
  def with_page
22
- attempts = 0
23
- begin
24
- attempts += 1
25
- # The block form is required: it's the only way Ferrum disposes the
26
- # browser context afterward. Closing just the page (as a bare
27
- # `create_page(new_context: true)` + `page.close` would) leaks a
28
- # context per call, which adds up fast in a long-lived pooled browser.
29
- browser.create_page(new_context: true) { |page| yield page }
30
- rescue *RECOVERABLE_ERRORS
31
- reset!
32
- retry if attempts < 2
33
- raise
23
+ ConcurrencyLimiter.around do
24
+ attempts = 0
25
+ begin
26
+ attempts += 1
27
+ # The block form is required: it's the only way Ferrum disposes the
28
+ # browser context afterward. Closing just the page (as a bare
29
+ # `create_page(new_context: true)` + `page.close` would) leaks a
30
+ # context per call, which adds up fast in a long-lived pooled browser.
31
+ browser.create_page(new_context: true) { |page| yield page }
32
+ rescue *RECOVERABLE_ERRORS
33
+ reset!
34
+ retry if attempts < 2
35
+ raise
36
+ end
34
37
  end
35
38
  end
36
39
 
@@ -0,0 +1,40 @@
1
+ require "concurrent/atomic/semaphore"
2
+
3
+ module HtmlToPdf
4
+ # Bounds how many conversions may run against the shared BrowserPool
5
+ # browser at once. Configured via HtmlToPdf.configuration.max_concurrent_renders
6
+ # (nil, the default, means unbounded — today's exact behavior, no overhead).
7
+ #
8
+ # Exists because BrowserPool is one Chrome process per Ruby process (see
9
+ # docs/architecture.md's scaling note): a web app under normal load rarely
10
+ # needs this, but a Sidekiq/Solid Queue pool with many worker threads all
11
+ # calling HtmlToPdf::GenerateJob at once can otherwise pile an unbounded
12
+ # number of concurrent Page.printToPDF calls onto that one process.
13
+ module ConcurrencyLimiter
14
+ MUTEX = Mutex.new
15
+
16
+ module_function
17
+
18
+ def around
19
+ limit = HtmlToPdf.configuration.max_concurrent_renders
20
+ return yield unless limit
21
+
22
+ semaphore_for(limit).acquire { yield }
23
+ end
24
+
25
+ def semaphore_for(limit)
26
+ MUTEX.synchronize do
27
+ @semaphore = Concurrent::Semaphore.new(limit) if @semaphore.nil? || @limit != limit
28
+ @limit = limit
29
+ @semaphore
30
+ end
31
+ end
32
+
33
+ def reset!
34
+ MUTEX.synchronize do
35
+ @semaphore = nil
36
+ @limit = nil
37
+ end
38
+ end
39
+ end
40
+ end