Every Rails app that generates invoices, reports, or certificates eventually hits the same wall: PDF generation is slow, and doing it inside a web request means a visitor is sitting there staring at a spinner while Chrome renders a 40-page document in the background of your server process. HtmlToPdf is a gem built around a simple idea — render your actual Rails view, with its real CSS and layout, through a real headless Chrome instance — and its 4.0 release adds the obvious next step: doing that rendering in a background job instead of inside the request.
This post is a practical walkthrough: what the gem actually does, how the background-job piece works with a made-up example, why it holds up well in production, and how it stacks up against the other usual suspects — Grover, WickedPdf, and Prawn.
1. What HtmlToPdf actually is
HtmlToPdf’s core pitch is narrow and specific: it renders an existing Rails controller action — the same ERB, the same layout, the same CSS — to a PDF, by pointing a real headless Chrome instance at it. That’s a meaningfully different approach from two other common strategies:
- wkhtmltopdf-based gems (WickedPdf, PDFKit) use a bundled WebKit build that hasn’t kept pace with the web platform — no flexbox, no CSS Grid, and it’s built on an upstream project that’s gone unmaintained.
- Prawn doesn’t render HTML or CSS at all — you build the PDF’s layout from scratch using Prawn’s own drawing primitives. Great for pixel-perfect forms and checks; useless if you already have a styled view you want reproduced exactly.
HtmlToPdf drives Chrome directly over the Chrome DevTools Protocol, via the Ferrum gem — no Node.js, no Puppeteer, nothing outside the Ruby/Chrome boundary. And rather than spawning a fresh Chrome process per request (slow, and a good way to run your server out of memory under load), it keeps one pooled Chrome process per Ruby process, handing each conversion its own isolated browser context, and restarting the pooled instance automatically if it crashes.
Wiring it up is a one-time, three-line change:
class ApplicationController < ActionController::Base include HtmlToPdf around_action :html_to_pdfendAnd then any view becomes downloadable as a PDF just by asking for the :pdf format:
<%= link_to "Download Invoice", invoice_path(@invoice, format: :pdf) %>That’s genuinely it for the synchronous path — no separate PDF template, no second render call. It’s a real around_action, which the gem’s own docs are careful to point out: it’s not a before_action quietly re-running your action against a throwaway controller behind the scenes. Your normal callbacks, instance variables, and rescue_from handlers all behave exactly as they would for a normal HTML request.
Note
New in 4.0: background rendering. Everything above still works unchanged. The new piece is
HtmlToPdf.generate_later, which does the same render, but through ActiveJob instead of inline
— which is what the rest of this post is actually about.
2. A worked example: rendering a weekly report in the background
Say you run a small SaaS product, and once a week a customer can click “Download weekly report” to get a PDF summary of their account activity. That report pulls in a month of chart images and a long activity table — exactly the kind of PDF that’s slow enough to make synchronous rendering a bad idea.
Enqueue the render instead of rendering inline:
class ReportsController < ApplicationController def create account = current_user.account
job = HtmlToPdf.generate_later( controller: ReportsController, action: :show, assigns: { account: account, range: 1.week.ago..Time.current }, pdf_options: { print_options: { format: 'A4', landscape: true } }, store: { adapter: :active_storage, record: account, attachment: :weekly_report } )
render json: { job_id: job.job_id } endendA few things worth noticing here, in plain English:
- You’re not writing a special “PDF version” of the report action —
action: :showpoints at the exact same controller action a normal web request would hit.assigns:is how you hand it the instance variables that action’s view expects, since there’s no real HTTP request happening to populate them. store:tells the gem what to do with the finished PDF once Chrome is done rendering it. Here,adapter: :active_storageattaches the result directly onto theaccountrecord’sweekly_reportattachment — you’d set that up as an ordinaryhas_one_attached :weekly_reporton theAccountmodel, nothing HtmlToPdf-specific about it.
Checking on the job from anywhere — including a different process than the one that enqueued it:
status = HtmlToPdf::JobStatus.find(job.job_id)status.state # => "queued", "processing", "completed", or "failed"status.result # once completed: { adapter: :active_storage, blob_id: ..., key: ..., filename: ..., byte_size: ... }This is the part that trips people up, so it’s worth being explicit about why it works at all: JobStatus isn’t reading from the worker process’s memory — by default it’s backed by Rails.cache, which means your cache store has to actually be shared between the web process that enqueued the job and the worker process running it. If your development.rb is still using :memory_store, your web dyno’s “queued” status will never update, because the worker updating it is a completely separate process with its own memory. Point config.cache_store at something genuinely shared — :solid_cache_store, :redis_cache_store, :mem_cache_store — before you rely on this in anything beyond a single-process dev setup.
Picking a queue backend — this is where “plain ActiveJob” pays off. HtmlToPdf::GenerateJob is an ordinary ActiveJob::Base subclass. It doesn’t know or care what’s running underneath it. Switching backends is a Rails-level config change, not a gem-level one.
With Solid Queue (no extra services to run beyond your own app):
config.active_job.queue_adapter = :solid_queuebin/jobsWith Sidekiq (add it yourself — it’s not a dependency of the gem):
# Gemfilegem 'sidekiq'Sidekiq.configure_server { |c| c.redis = { url: ENV.fetch('REDIS_URL') } }Sidekiq.configure_client { |c| c.redis = { url: ENV.fetch('REDIS_URL') } }config.active_job.queue_adapter = :sidekiqbundle exec sidekiqEither way, the job class itself doesn’t change — the gem’s own position is that Good Job, Que, and Delayed Job all “work the same way” for exactly this reason: it’s ActiveJob all the way down.
If you need a tighter retry policy than the default, you don’t get to tune it through a config option — and there’s a specific, slightly unusual reason why. The built-in GenerateJob’s retry_on/discard_on rules are declared at require time, while your app’s Gemfile is loading — which happens before your own config/initializers/html_to_pdf.rb ever runs. There’s no config value you can set that would reach the class in time. The documented way around this is to subclass instead:
class WeeklyReportJob < ActiveJob::Base retry_on Ferrum::DeadBrowserError, wait: 10.seconds, attempts: 10
def perform(account_id, range) account = Account.find(account_id) pdf_bytes = HtmlToPdf::Renderer.render( controller: ReportsController, action: :show, assigns: { account: account, range: range } ) HtmlToPdf::Storage.store(pdf_bytes, adapter: :s3, key: "reports/#{account.id}/weekly.pdf") endendAnd if you want to cap how much Chrome work happens at once — reasonable, since there’s one shared browser pool per Ruby process — there’s a single config knob for it:
HtmlToPdf.configure do |config| config.max_concurrent_renders = 4endThat’s a semaphore around the shared browser, and it applies to both the synchronous path and background jobs equally.
3. Why it holds up in production
- No Node.js anywhere in the chain. If your stack is Rails and nothing else, that’s one less toolchain to install, version-pin, and keep patched in your deploy image.
- A pooled browser, not a spawned-per-request one. This is the single biggest reason a headless-Chrome PDF tool can or can’t survive production traffic — spawning a fresh Chrome process per request is a reliable way to run a box out of memory under any real load.
- Queue-agnostic by design. Because the background path is plain
ActiveJob::Basewith nothing Sidekiq- or Solid-Queue-specific in it, moving from one to the other later is a config change, not a rewrite. - A real
around_action. Your existingbefore_actions, instance variables, andrescue_fromhandlers behave normally — you’re not maintaining a parallel, PDF-only rendering path that can silently drift from the real one. - Validated print options, and header/footer templates that are opt-in specifically — which the gem treats as a deliberate security boundary (raw HTML templates are an injection surface if they’re ever built from anything other than trusted, static strings), not an oversight.
4. Conclusion, and how it compares to Grover, WickedPdf, and Prawn
| HtmlToPdf | Grover | WickedPdf / PDFKit | Prawn | |
|---|---|---|---|---|
| Renders your existing HTML/CSS view | Yes | Yes | Yes | No — own DSL |
| Engine | Chrome, direct via CDP (Ferrum) | Chrome, via Node.js + Puppeteer | wkhtmltopdf (unmaintained) | n/a |
| Modern CSS (flexbox, Grid) | Yes | Yes | No | n/a |
| Extra runtime beyond Ruby | Chrome/Chromium | Chrome + Node.js + Puppeteer | wkhtmltopdf binary | None |
| Pooled/reused browser process | Yes, built in | Depends on your own setup | n/a — CLI call per render | n/a |
| Built-in Rails controller integration | Yes, around_action |
Manual | Yes | Manual |
| Layout control | CSS | CSS | CSS (limited, old WebKit) | Direct PDF primitives, pixel-level |
The honest way to pick between these, in the same order HtmlToPdf’s own docs frame it:
- If the PDF has to look exactly like a view you’ve already styled, Prawn is off the table from the start — it has no HTML/CSS engine, by design, so there’s no version of “just point it at an ERB template.”
- If you want Chrome-quality rendering without adding Node.js to a Ruby stack that otherwise has none, that’s HtmlToPdf’s actual target use case.
- If a Node toolchain is already part of your stack for other reasons, or you specifically want Puppeteer’s own mature PDF API (native header/footer templates, its particular
waitUntilsemantics), Grover is a perfectly reasonable choice — the Node.js dependency costs you little if you’re already paying for it elsewhere. - If your layouts are simple enough that wkhtmltopdf’s rendering gap genuinely never surfaces, and a single static binary is worth more to you operationally than a full Chrome install, WickedPdf/PDFKit is still a legitimate, lower-footprint option — just go in aware that its underlying rendering engine isn’t actively maintained upstream.
- If you need pixel-exact control CSS simply can’t give you — gridded forms, checks, label sheets — Prawn is still the right tool, and no HTML-based renderer is going to out-compete it there.
HtmlToPdf’s real contribution in 4.0 isn’t the Chrome-rendering story — that’s been there from the start — it’s that background PDF generation no longer means wiring your own ActiveJob plumbing around Ferrum by hand. For a Rails app that already wants to stay out of the Node.js business, and that just gained a reason a PDF needs to happen outside the request cycle, that’s a meaningful, well-scoped upgrade.