HTML to PDF: how the pipeline works and how to get it right
Rendering HTML to PDF is the right choice when the document already exists as a web template, when typography and CSS layout matter more than byte-level control of the file, or when the people maintaining the template know CSS and not a PDF library. It is the wrong choice when the layout is fixed and small, when the output must be tiny or structurally clean, or when the input comes from people you do not trust. This page covers the pipeline itself, independent of language; the per-language guides show how to drive it from JavaScript, Python, PHP, C#, Java and Go.
The pipeline#
Whatever engine you use, the same four stages run: the HTML is parsed and styled, a layout engine breaks the styled boxes into pages following the CSS Paged Media rules, each page is painted, and a PDF writer turns the painted pages into page objects, content streams and embedded fonts.
Two consequences follow. First, the PDF you get is the browser's print output, not a copy of the screen: print media queries apply, backgrounds are dropped unless you ask for them, and @page rules decide the paper. Second, the writer is generic. It embeds fonts as subsets, emits one content stream per page and knows nothing about the document's meaning unless the engine produces tags, so the result is larger and flatter than the same document built with a PDF library.
Choosing an engine#
| Engine | What it is | CSS support | JavaScript | Page margin boxes, counters | Licence | Cost in production |
|---|---|---|---|---|---|---|
| Headless Chromium (Puppeteer 25, Playwright 1.64) | Blink layout with Skia's PDF backend, the same path as Print in Chrome | Everything Chrome supports: Grid, Flexbox, variable fonts, modern typography | Yes, full | Yes since Chrome 131, plus header and footer templates from the driver | Chromium BSD; Puppeteer Apache-2.0; Playwright Apache-2.0 | A browser process per worker, 100 MB or more each; needs sandboxing |
| WeasyPrint 70 | Python CSS paged-media engine with its own writer | CSS 2.1 and much of CSS 3 including Grid and Flexbox; built for print | No | Yes, the most complete open-source implementation | BSD-3-Clause | Pure Python plus Pango and cairo libraries; slow on large documents |
| Prince | Commercial paged-media engine from YesLogic | Very complete print CSS, PDF/A and PDF/UA output, footnotes, cross references | Limited, own engine | Yes, reference quality | Commercial per server | Single binary, fast; licence fee |
| DocRaptor, PDFreactor | Hosted Prince (DocRaptor) and a commercial Java engine (PDFreactor) | As Prince; PDFreactor comparable | PDFreactor yes | Yes | Commercial | Per document or per server; data leaves your network with hosted services |
| wkhtmltopdf | QtWebKit from around 2012 with a patched Qt | No Grid, no Flexbox, old font handling | Old engine | No; command-line header and footer options | LGPL-3.0 | Repository archived 2 January 2023; unmaintained, unpatched |
For new work the choice is between Chromium and WeasyPrint, with Prince where budget allows and print fidelity is the product. Chromium wins on CSS coverage and JavaScript-rendered content; WeasyPrint wins on paged-media features, deployment simplicity and the absence of a browser attack surface. wkhtmltopdf should not be chosen for anything new: it has not received a security fix since the project was archived, and its layout engine predates most of the CSS your templates use.
Print CSS that matters#
The stylesheet does more work in this pipeline than any option you pass to the driver. These rules cover most documents.
/* Paper and margins. Values with units; A4, Letter, Legal and the other named sizes are accepted. */
@page { size: A4; margin: 20mm 15mm 25mm 15mm; }
@page :first { margin-top: 35mm; } /* room for a letterhead on page one */
@page landscape-table { size: A4 landscape; } /* a named page, applied with `page: landscape-table` */
/* Breaks. Modern names first; the page-break-* aliases still work everywhere. */
h2 { break-after: avoid; } /* keep a heading with what follows */
tr, figure, .card { break-inside: avoid; } /* never split these */
.chapter { break-before: page; } /* start on a new page */
p { orphans: 3; widows: 3; } /* no lonely lines at page edges */
/* Tables: repeat the header row on every page, let rows flow. */
thead { display: table-header-group; }
tfoot { display: table-footer-group; }
/* Backgrounds and colours. Browsers drop them for print unless told otherwise. */
th { background: #eef; print-color-adjust: exact; }
/* Running headers and footers with page numbers (CSS Paged Media margin boxes). */
@page {
@top-right { content: "Invoice 1001"; font: 9pt sans-serif; color: #555; }
@bottom-center { content: "Page " counter(page) " of " counter(pages); font: 9pt sans-serif; }
}Margin boxes are the standard way to put running headers and page numbers on paper. WeasyPrint and Prince have supported them for years. Chromium added them in Chrome 131 (October 2024), and the example above was verified on the headless Chrome used for this page: a three-page document produced "Page 1 of 3", "Page 2 of 3" and "Page 3 of 3" in the bottom margin, extractable as text. If you must support older Chromium builds, Puppeteer and Playwright offer headerTemplate and footerTemplate instead, shown below. Do not use both at once; they fight for the same margin space.
Two rules of thumb for the stylesheet itself. Keep one authority for page size: either @page { size } with preferCSSPageSize: true, or the driver's format option, never both. And write a real print stylesheet rather than reusing the screen one: hide navigation, set a fixed body width in millimetres or points rather than viewport units, avoid position: fixed (it repeats on every page in Chromium) and vh units (the viewport is the page box, which is rarely what you meant).
A complete Chromium example#
This script was run with Node 26, puppeteer-core 25.16.0 and the Chrome installed on the build machine (Chrome 156, which the output names as Skia/PDF m156 in its producer string). It produced a three-page, tagged, 108 KB PDF whose text extracts cleanly and whose header row repeats on each page.
import puppeteer from 'puppeteer-core';
import { writeFileSync } from 'node:fs';
// puppeteer-core does not download a browser; point it at the one you manage.
const executablePath = process.env.CHROME_PATH || 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe';
const html = `<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>Invoice 1001</title>
<style>
@page { size: A4; margin: 20mm 15mm 25mm 15mm; }
body { font: 11pt/1.4 system-ui, sans-serif; }
table { border-collapse: collapse; width: 100%; }
thead { display: table-header-group; }
tr { break-inside: avoid; }
th, td { border-bottom: 1px solid #ccc; padding: 2mm 1mm; text-align: left; }
th { background: #eef; print-color-adjust: exact; }
</style></head>
<body>
<h1>Invoice 1001</h1>
<table><thead><tr><th>Item</th><th>Qty</th><th>Price</th></tr></thead>
<tbody>${Array.from({ length: 60 }, (_, i) => `<tr><td>Line item ${i + 1}</td><td>1</td><td>12.50 EUR</td></tr>`).join('')}</tbody>
</table>
</body></html>`;
const browser = await puppeteer.launch({ executablePath, headless: true });
try {
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle0' }); // wait for images and fonts referenced by the HTML
await page.evaluateHandle('document.fonts.ready'); // belt and braces; page.pdf also waits for fonts by default
const pdf = await page.pdf({
preferCSSPageSize: true, // @page { size } wins over the format option
printBackground: true, // default is false: no backgrounds, no th shading
margin: { top: '20mm', right: '15mm', bottom: '25mm', left: '15mm' },
displayHeaderFooter: true, // default is false
headerTemplate: '<div></div>', // an empty header, or Chromium prints the date and title
footerTemplate: '<div style="font-size:9px;font-family:sans-serif;width:100%;text-align:center;color:#555;">Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>',
});
writeFileSync('invoice.pdf', pdf); // Uint8Array
} finally {
await browser.close();
}Three details are worth knowing about the template options. The header and footer are rendered inside the page margin, so the margin must be large enough to hold them or they are clipped to nothing; margin passed to page.pdf applies in that case even if the CSS sets its own. The templates do not inherit the page's stylesheet: use inline styles and set an explicit font-size, because the default is very small. And the special classes date, title, url, pageNumber and totalPages are filled in by Chromium when they appear on an element inside the template.
The Playwright version is almost identical. Playwright manages its own browser builds (npx playwright install chromium), and its page.pdf is implemented for Chromium only.
import { chromium } from 'playwright';
const browser = await chromium.launch();
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle' });
await page.pdf({
path: 'invoice.pdf',
preferCSSPageSize: true,
printBackground: true,
margin: { top: '20mm', right: '15mm', bottom: '25mm', left: '15mm' },
displayHeaderFooter: true,
headerTemplate: '<div></div>',
footerTemplate: '<div style="font-size:9px;width:100%;text-align:center;">Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>',
tagged: true, // Playwright defaults to false; Puppeteer defaults to true
});
await browser.close();Fonts#
The example above asked for system-ui and got Segoe UI, because it ran on Windows. On a Linux server it would get whatever fontconfig finds, often DejaVu Sans, and the invoice would look different. Fonts are the most common cause of "works on my machine" in this pipeline, and the fix is to stop depending on the machine:
- Ship the font files with the template and reference them with
@font-face { src: url('fonts/Inter.woff2') }using paths the renderer can reach (file://paths for local HTML, or a local HTTP server). - Wait for them:
document.fonts.readyresolves when declared fonts have loaded, and Puppeteer'swaitForFontsoption (default true) makespage.pdfwait as well. - Check the result: the fonts in the PDF should be the ones you shipped, embedded as subsets. The PDF inspector lists them; the fonts page explains what "embedded subset" means and why a missing font turns into Arial.
Chromium embeds fonts as TrueType or CFF subsets inside composite (Type 0) fonts with a ToUnicode map, so text extraction and search work. It does not embed the fourteen standard fonts either; if your CSS says Helvetica, the server's substitute gets embedded.
Images and remote resources#
Images are fetched by the engine, so they must be reachable from the renderer, not from the user's browser. Data URIs and local files avoid the network entirely; HTTP URLs need the renderer to resolve them, and networkidle0 only waits for requests that started before it was called. Chromium rasterizes nothing it does not have to: an SVG stays vector, a JPEG is embedded as a JPEG (DCTDecode) and a PNG is recompressed with Flate, so a 300 PPI photograph produces a 300 PPI image in the file. The compression page covers what that does to file size.
Security#
A rendering engine executes the document you give it. If any part of that document comes from a user, a customer or a third-party system, treat the renderer as untrusted code running in your network:
- Server-side request forgery.
<img src="http://169.254.169.254/latest/meta-data/">or<link rel=stylesheet href="http://internal-host/">makes the renderer fetch internal URLs. Mitigate with a request interceptor that allows only an explicit list of hosts (Puppeteer:page.setRequestInterception(true)andrequest.abort()for anything else), or run the browser in a network namespace that can reach nothing but your asset host. - Local files.
file:///etc/passwdin an<iframe>or<img>reads the server's disk. Serve templates over HTTP rather thanfile://, and keep the interceptor rule forfile:requests. - JavaScript. Scripts in untrusted HTML run with full browser capability. Disable it (
page.setJavaScriptEnabled(false)) unless the template genuinely needs it, and sanitize the HTML first with an allowlist-based sanitizer. - Resource exhaustion. A document can be 100,000 pages or a single element 10 metres tall. Set
timeoutonpage.pdf, cap page counts withpageRanges, and run with a memory limit. - Isolation. Run the browser in its own container or VM with no credentials, no persistent profile and no access to the application database. Chromium's own sandbox helps, but a browser that someone else can script should not share a host with your secrets.
WeasyPrint has no JavaScript and a smaller surface, but it still fetches URLs; its url_fetcher hook is the place to apply the same allowlist.
Scaling#
Launching a browser costs seconds; rendering a page costs milliseconds. Keep a pool of warm browser instances, open a new page (tab) per job, close the page afterwards, and recycle a browser after a few hundred jobs to contain memory growth. Run one page per job rather than many pages in one browser context when jobs belong to different users, so a crash or a leak cannot cross tenants. Size workers by memory, not CPU: each Chromium instance wants 100 to 300 MB, more with large images. Queue jobs; do not render inside a web request that a user is waiting on unless the document is small and the pool is already warm. Serverless platforms can run Chromium, but cold starts and the binary size usually make a small pool of long-lived workers cheaper.
What you get, and what you do not#
The output of the example was a tagged PDF 1.7 file: Chromium emits a structure tree from the HTML semantics when tagged is on, which Puppeteer enables by default and Playwright does not. That gives screen-reader users headings and tables rather than a flat run of text, and it is the only practical way to get tagged output from a browser pipeline. The page box is Chromium's own rounding of A4 to whole CSS pixels: the file reports 594.96 × 841.92 pt rather than the exact 595.28 × 841.89 pt, which matters only if a print workflow checks the box against a nominal size. The page-boxes page explains the boxes; the units page explains the rounding.
Metadata comes from the HTML: the <title> becomes the PDF title, the producer string is Skia's. Anything else, such as an author or keywords, has to be set afterwards with a PDF library, as described on the metadata page. Form fields, bookmarks from headings, attachments and digital signatures are also post-processing steps; the browser pipeline does not produce them.
When not to use it#
Reach for a PDF library instead when the document is a label, a certificate or a form with a fixed layout; when you need PDF/A or PDF/X conformance from the generator rather than from a converter afterwards; when files must be small (a browser-rendered invoice is typically 50 to 150 KB, a library-drawn one 5 to 20 KB); when the server cannot run a browser; or when the HTML is untrusted and you cannot afford the isolation described above. The developers hub lays out the three approaches side by side.
Sources
- Puppeteer API, PDFOptions (defaults for format, margin, printBackground, preferCSSPageSize, displayHeaderFooter, tagged, waitForFonts)
- Playwright API, page.pdf()
- W3C CSS Paged Media Module Level 3 (@page, margin boxes, page counters)
- Chrome for Developers, "Add content to the margins of web pages when printed using CSS" (Chrome 131, October 2024)
- MDN, break-inside
- MDN, print-color-adjust
- WeasyPrint 70.0 documentation, First Steps (requirements, Windows installation)
- wkhtmltopdf repository (archived 2 January 2023)
- Prince (YesLogic)
- Chromium headless mode documentation