Imagine a NestJS API with a "Download invoice" button. Each click launches headless Chrome, renders an HTML template, and streams the PDF back in the same request. It works in development. Then month-end arrives, a few hundred customers click at once, response times climb, and the container restarts after being killed for running out of memory. The invoices that did render show empty boxes where a customer's name was written in Japanese.
None of this means PDF generation is hard. It means a PDF is a batch job dressed up as an HTTP response.
A PDF setup that holds up under load comes down to a few decisions:
- Pick the renderer that fits the document, not the first tutorial you find.
- Render in a background worker, not in the request.
- Give the container the libraries, fonts, and memory that Chrome needs.
- Treat the HTML you render as untrusted input.
- Store the finished file once and serve it through a short-lived link.
- In the EU, check whether your invoice PDF also needs to be a structured e-invoice.
Choose a renderer: a headless browser or a PDF library
There are two families of tools, and they fail in different ways.
Headless browsers render HTML and CSS, so designers can work in a familiar format:
- Puppeteer controls Chrome. It's at version 25.19.0 as of November 2026, under the Apache-2.0 license. Its PDF options reference lists defaults worth knowing: the paper format is letter, backgrounds don't print unless
printBackgroundis true, and the timeout is 30 seconds. - Playwright has a similar page.pdf method. PDF output is generally tied to Chromium, so confirm in the docs for your version which browsers support it before planning around another engine.
- Gotenberg is an MIT-licensed, Docker-based API that converts HTML and office documents to PDF. It's at version 9 as of November 2026, per its GitHub repository. It moves Chrome out of your API container entirely, which removes much of the container setup work described below.
PDF libraries draw the document from code, with no browser:
- pdfkit (MIT) gives you low-level drawing, text, and font embedding.
- pdfmake (MIT) describes documents as JSON. It lists repeated table headers after page breaks and PDF/A support among its features in its README.
- @react-pdf/renderer (MIT) builds PDFs from React components, which suits teams that already write React.
- pdf-lib is still widely recommended, but as of November 2026 its last release was in November 2021. Factor that into a new project.
A rough rule: invoices and reports that look like web pages are easier in a browser, because CSS handles layout and you can preview the template. Very high volumes of simple, fixed-layout documents can be cheaper with a library, because there's no browser process. Measure with your real documents before committing.
Don't render inside the request
Rendering a PDF ties up resources for much longer than a typical API call. Doing it in the request handler means one slow document delays everything else on that instance, and a traffic spike becomes a memory spike.
Move the work to a queue instead. With NestJS and BullMQ, the flow looks like this:
- The API validates the request, enqueues a job with the invoice ID, and returns
202 Acceptedwith a job ID. - A worker loads the data, renders the PDF, uploads it to storage, and records the file location.
- The client polls a status endpoint, or receives a notification, and then requests a download link.
The NestJS queues documentation covers the @nestjs/bullmq setup: a consumer class extends WorkerHost and implements process(). Run workers in a separate deployment from the API if you can, so a rendering spike can't starve request handling. For the queue basics, see the earlier post on background jobs with BullMQ in NestJS.
Make the job idempotent. If an invoice PDF already exists for that invoice version, return the stored file instead of rendering it again.
Worker settings that matter
A few BullMQ details decide whether PDF workers behave under load:
- Concurrency. The concurrency guide describes a per-worker limit on parallel jobs. Start low for PDF work. Each concurrent render needs its own memory.
- Stalled jobs. If a worker keeps the Node.js event loop busy, BullMQ can't renew the job's lock, and the job is treated as stalled. By default a job can stall once before it fails, per the stalled jobs guide. CPU-heavy layout in the main process is a common cause.
- Sandboxed processors. The docs recommend sandboxed processors for CPU-intensive work, so it runs isolated from the worker's main process. In NestJS, the documentation notes that dependency injection isn't available in a forked processor, so pass IDs in the job and load what you need inside the processor.
- Timeouts. As of November 2026, BullMQ doesn't provide a built-in job timeout. The timeout pattern uses a timer with an
AbortControllerand throwsUnrecoverableErrorwhen retrying won't help. Pair it with Puppeteer's owntimeoutoption.
My reading of these docs: sandboxing matters most for libraries like pdfkit and pdfmake, which lay out the document inside the Node process. With Puppeteer, most of the rendering happens in separate Chrome processes, but parsing large data sets and building HTML still run in Node.
Running Chrome in a container
Most "it works locally, fails in Docker" reports trace back to the same few causes. The Puppeteer troubleshooting guide covers them:
- Missing system libraries. The guide says the bundled Chrome for Testing is missing shared library dependencies it needs, and its sample Dockerfile installs a system Chrome package to pull them in.
- Missing fonts. The same sample installs font packages for Chinese, Japanese, Arabic, Hebrew, Thai, and other scripts. Without them, those characters can render as empty boxes.
- The sandbox. The guide says running without a sandbox is "strongly discouraged". The sample adds a non-root user so
--no-sandboxisn't needed. Many tutorials add--no-sandboxwithout comment. Don't copy that line unless you understand what you're giving up. - An init process. The sample Dockerfile notes that the
--initflag ofdocker runreaps zombie processes, and the Docker guide asks for an init process too, so Chrome's child processes are cleaned up instead of left behind.
The official image at ghcr.io/puppeteer/puppeteer runs the browser in sandbox mode and, per the same guide, needs the SYS_ADMIN capability. Some platforms don't allow that. If yours doesn't, a separate rendering service such as Gotenberg is often the cleaner option.
Older guides also tell you to raise /dev/shm or pass --disable-dev-shm-usage, because Chrome uses shared memory and containers can give it a small default. The current Puppeteer docs no longer cover this, so treat it as something to check on your platform rather than a required flag.
Memory: three different limits
When a PDF worker is killed for running out of memory, it helps to know which limit you hit:
- The Node.js heap.
--max-old-space-sizecaps the size of V8's old memory section, per the Node.js CLI docs. It does not limit Chrome, which runs as separate processes. - Chrome's processes. Each browser and page uses memory outside the Node heap. That usage depends heavily on the document, so measure it instead of trusting a figure from a blog post.
- The container limit. The Docker resource constraints page explains that when the container runs out of memory, by default the kernel kills processes inside it. That applies to the total of Node and Chrome.
To size this, render your largest realistic document at your chosen concurrency, watch memory with docker stats or your platform's metrics, and set the container limit with headroom. Then cap concurrency so the worst case stays below it. For a deeper look at how containers and Node see memory, see the earlier post on Docker container memory limits.
Reusing one browser across jobs avoids repeated startup cost. Launching a fresh browser per job gives better isolation and cleans up leaks. The Puppeteer docs describe both, plus isolated browser contexts, without recommending one. A common middle ground is one browser per worker, a new context per job, and a browser restart after a set number of jobs.
Fonts, non-Latin text, and page breaks
Fonts and pagination produce most "the PDF looks wrong" bugs:
- Wait for fonts. Puppeteer's
waitForFontsoption defaults to true and waits fordocument.fonts.ready. MDN describes that promise as resolving once fonts have finished loading. Prefer fonts bundled in the image or inlined in the template over fonts fetched from the internet during rendering. - Embed fonts in pdfkit. The pdfkit text docs list the 14 standard PDF fonts and support for embedding TrueType, OpenType, and WOFF fonts. The standard fonts aren't designed for scripts like CJK or Arabic. Embed a font that covers the characters your customers actually use, including names and addresses.
- Keep rows together. break-inside with the value
avoidkeeps a table row or a totals block from splitting across pages. - Repeat table headers. Chromium repeats a table's
theadat the top of each printed page; a 2016 Chromium change made that the default. Test it with your own long tables, because very tall first rows can behave differently. - Page size and margins. Use the CSS @page rule for size and margins, and set
preferCSSPageSizeto true so Puppeteer uses it instead of the default letter size. EU customers usually expect A4 and US customers letter, so make it a setting. - Backgrounds and colors. Puppeteer leaves backgrounds out by default. Set
printBackground, and consider print-color-adjust with the valueexactfor colored table stripes and badges. - Headers and footers. Puppeteer's header and footer templates support classes such as
pageNumberandtotalPagesfor "Page 2 of 5" footers. They render separately from the page, so inline their styles.
Lock down the renderer
A headless browser on your server will fetch whatever the HTML asks for. The OWASP SSRF prevention cheat sheet names server-side rendering such as HTML to PDF as a server-side request forgery risk. An injected image or iframe can point at internal services, file:// paths, or the cloud metadata endpoint that hands out credentials.
The OWASP document rendering cheat sheet lists the main controls:
- Turn JavaScript off when the template doesn't need it.
- Deny outbound network traffic by default, and allow only the origins the document needs.
- Run rendering as a non-root user, and don't launch with
--no-sandboxfor untrusted input. - Set time, memory, and output-size limits.
In practice, for a NestJS invoice service:
- Never accept a URL from the client and render it. Render your own templates with your own data.
- Use a template engine that escapes by default. In Handlebars, double braces HTML-escape values, while triple braces don't. Avoid triple braces for anything a user typed, such as a company name or address line.
- Use Puppeteer's request interception to abort every request that isn't for an allowed asset, or load the HTML with all assets inlined and block the network entirely.
- Keep the rendering worker on a network with no route to internal services.
Store once, serve through short-lived links
Once the worker produces the file, upload it to object storage and record its location against the invoice. An issued invoice shouldn't be regenerated later from changed data. Store it once and serve that same file.
For Azure Blob Storage, the SAS overview has three recommendations:
- Use a user delegation SAS, which is secured with Microsoft Entra credentials instead of the account key.
- Use near-term expiration times and read-only permissions.
- Set the start time at least 15 minutes in the past, or leave it out, to avoid clock-skew failures.
Per the user delegation SAS reference, the delegation key itself is valid for up to seven days. The response-header parameter rscd sets the Content-Disposition header on the download. Use it to give the file a friendly name and force a download.
On Content-Disposition, inline displays the PDF in the browser and attachment downloads it. MDN recommends sending both filename and filename* so non-ASCII file names work everywhere.
On AWS, S3 presigned URLs do the same job. They grant time-limited access and can last up to seven days when created with the CLI.
Issue a fresh link each time an authorized user asks for one, rather than emailing a long-lived link. The earlier post on large dataset exports covers the same pattern for CSV files.
Tagged PDFs, PDF/UA, and PDF/A
Two standards come up when PDFs are official documents:
- Accessibility. As of November 2026, Puppeteer's experimental
taggedoption defaults to true and generates a tagged PDF, while Playwright'staggedoption is off by default, so check the setting if you use Playwright. Tags help screen readers, but a tagged PDF isn't automatically conformant with PDF/UA, the ISO 14289 accessibility standard described by the Library of Congress. Use real headings, table headers, alt text, and a document language in your template. - Archiving. PDF/A is a constrained PDF intended for long-term archiving. The Library of Congress PDF/A-3 entry notes it also allows embedded files. Puppeteer has no PDF/A option. If you need PDF/A, use a tool that produces and validates it, such as Gotenberg, or pdfmake, which lists PDF/A support.
In the EU, an invoice PDF may not be an e-invoice
This is the part many PDF tutorials skip, and for EU invoices it may matter more than rendering speed.
The European Commission's eInvoicing page says an e-invoice is issued, sent, and received in a structured data format. Invoices issued as PDF or Word files don't count, and the European standard EN 16931 defines the structure. A nicely rendered PDF is still an unstructured invoice.
That distinction is becoming a legal requirement in parts of the EU:
- Germany. Per the Federal Ministry of Finance FAQ, domestic businesses have had to be able to receive e-invoices since 1 January 2025. Transition rules allow other invoice formats for B2B until 31 December 2026, or until the end of 2027 for businesses with prior-year turnover up to €800,000. A plain PDF falls under "other invoices", but ZUGFeRD from version 2.0.1 qualifies as an e-invoice, except its MINIMUM and BASIC-WL profiles.
- Across the EU. The VAT in the Digital Age package entered into force on 14 April 2025. It lets member states introduce mandatory e-invoicing under certain conditions, and digital reporting based on e-invoicing applies to cross-border B2B transactions from 1 July 2030.
Hybrid formats bridge the gap. ZUGFeRD, and its French counterpart Factur-X, combine a human-readable PDF with structured XML based on EN 16931. Gotenberg lists Factur-X support. In Germany's rules, the XML part is the authoritative one, so the data must be correct in the XML, not just in the visible layout.
If you sell B2B in the EU, treat the PDF as the human copy and plan the structured data separately. Check national rules and dates with your tax adviser, since they differ by country and are changing. This section is an overview, not legal or tax advice.
Checklist
- Pick a renderer deliberately: a headless browser for HTML layouts, a library for simple high-volume documents, or a separate service like Gotenberg to keep Chrome out of your API.
- Render in a BullMQ worker, return
202with a job ID, and make jobs idempotent. - Keep worker concurrency low, add your own job timeout, and sandbox CPU-heavy processors.
- In Docker, install the system libraries and fonts Chrome needs, use an init process, and keep the sandbox on.
- Size memory for Node, Chrome, and the container together, based on your measurements.
- Embed fonts that cover your customers' scripts, wait for fonts, and test page breaks, repeated headers, and backgrounds.
- Render only your own escaped templates, block network requests, and isolate the worker.
- Store each issued document once, and serve it through a short-lived, read-only link with a proper file name.
- Use the tagged output for accessibility, and a validating tool when you need PDF/A.
- For EU B2B invoices, check whether you need EN 16931 structured data, such as ZUGFeRD or Factur-X, not just a PDF.



