← Back to Blog

Convert HTML to PDF: Headless Chrome and Playwright, Tested

I printed the same 60 line invoice to PDF with the Chrome command line and with Playwright, and compared what came out. One run printed my local file path on every page, one silently switched A4 to US Letter, and one dropped the coloured header. Here are the flags that fix each, and the print CSS that worked.

The short answer: for one file, use the Chrome you already have. Press Cmd+P or Ctrl+P and choose Save as PDF, or run Chrome headless from a terminal with --print-to-pdf and --no-pdf-header-footer. For anything automated, drive Chrome with Playwright or Puppeteer and pass two options their defaults leave off: use the CSS page size, and print backgrounds. Then control the layout with an @page rule in your CSS.

The test page

Everything here was run on November 27, 2026, on macOS 26.7.3 with Google Chrome 158 and Playwright 1.65 for Python. The test page is an invoice with things that usually go wrong:

<title>Invoice 0042 draft</title>
@page { size: A4; margin: 20mm 15mm;
  @bottom-right { content: "Page " counter(page) " of " counter(pages); } }
.band { background: #1a4d8f; color: #fff; }   /* coloured header strip */
tr    { break-inside: avoid; }                 /* never split a row */
<table> with a <thead> and 60 rows, so it runs onto a second page

Headless Chrome from the terminal, and what the default header leaks

# macOS path. On Linux the binary is usually google-chrome or chromium.
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --headless \
  --no-pdf-header-footer --print-to-pdf=invoice.pdf file:///path/to/invoice.html

Result: 86,884 bytes, 2 pages, A4 (595 x 842 points), the blue band printed, the table header repeated at the top of page 2, and "Page 1 of 2" bottom right from my @page rule.

Without --no-pdf-header-footer, Chrome adds its own header and footer. I extracted the text of that version to see exactly what they contain:

27/11/2026, 04:07 Invoice 0042 draft
file:///private/tmp/.../h2p/invoice-nobox.html 1/2

(I shortened the path.) The header is the print date and the page's <title>, which here includes the word "draft". The footer is the full local path of the HTML file, which can include your user name and folder layout. That is on every page of a document you may be about to send to a customer. Two details I found along the way: when the page defines its own @bottom-right box, Chrome's footer with the path is replaced, but its header with the date and title still prints. And text extraction reads the path as file:/// with an "fi" ligature, so searching the PDF for file:// finds nothing. Always pass the flag.

Playwright: two defaults that change your output

Playwright drives the same Chrome engine and is what I'd use for anything repeatable. With channel="chrome" it uses the installed Chrome, so there is no separate browser download:

from playwright.sync_api import sync_playwright
import pathlib

url = pathlib.Path("invoice.html").resolve().as_uri()
with sync_playwright() as p:
    browser = p.chromium.launch(channel="chrome")
    page = browser.new_page()
    page.goto(url)
    page.pdf(path="pw-default.pdf")
    page.pdf(path="pw-css.pdf", prefer_css_page_size=True, print_background=True)
    browser.close()
pw-default.pdf   24,848 bytes  2 pages  612 x 792 pt (US Letter)
pw-css.pdf       24,871 bytes  2 pages  595 x 842 pt (A4)

The page size. My CSS says A4, but the default call produced US Letter. page.pdf() uses its own paper size unless you set prefer_css_page_size=True. If you send invoices to customers in Europe and they print at the wrong size, this is the reason.

The background. In the default version, the blue band was gone, and the white heading text on it became faint grey text on white. With print_background=True it came back. The Chrome command line printed it without being asked, so the same HTML looks different depending on how you call Chrome. Puppeteer has the same two options with the same defaults (preferCSSPageSize and printBackground, both false, per the Puppeteer PDFOptions reference). The Playwright options are in the page.pdf documentation.

I didn't check why the Playwright files are under a third the size of the command line ones. Both had the same three subset Helvetica fonts and no images. If size matters, measure your own output.

The print CSS that worked

All three of these behaved as expected in Chrome 158, in both the command line and Playwright output:

  • @page { size: A4; margin: ... } sets paper and margins. It only wins in Playwright and Puppeteer when you ask for the CSS page size, as above.
  • Margin boxes such as @bottom-right with counter(page) and counter(pages) gave "Page 1 of 2" and "Page 2 of 2". This saves you from Chrome's header and footer templates entirely. MDN's @page reference lists the box names.
  • A real <thead> repeated at the top of page 2. The column headings were the first table text on the second page in every version.

Two more rules I'd add to any invoice or report: tr { break-inside: avoid; } so a row never splits across pages, and h2 { break-after: avoid; } so a heading never sits alone at the bottom of a page. For backgrounds in the browser's own print dialog, add print-color-adjust: exact to the elements that need them.

A missing web font does not stop the PDF

I also tested a heading set in a Google Font. On the machine I tested on, Chrome couldn't reach Google Fonts at all (the request failed with net::ERR_SOCKET_NOT_CONNECTED, a network restriction on that machine). That turned into a useful test of failure. The Chrome command line and Playwright both produced a PDF anyway, with the heading in a fallback cursive font, no error and no warning. document.fonts.check("16px Lobster") even returned true, because that check reports whether loading is still needed, not whether the font you asked for is the one in use.

So in an automated pipeline, check for failed requests yourself and fail the job:

failed = []
page.on("requestfailed", lambda r: failed.append((r.url, r.failure)))
page.goto(url, wait_until="networkidle")
if failed:
    raise SystemExit(f"not printing, {len(failed)} request(s) failed: {failed[:3]}")
page.pdf(path="out.pdf", prefer_css_page_size=True, print_background=True)

Better still, serve the fonts from your own server or embed them with @font-face pointing at local files, so the PDF never depends on a third party being reachable at print time.

The PDF keeps your page title

Every version had the PDF Title field set to Invoice 0042 draft, copied from the HTML <title>. PDF readers show it in the window title. Set the title in your template to what the customer should see. The PDF optimization guide covers metadata in more detail, including a check script that catches it before a file ships.

wkhtmltopdf and canvas exports

wkhtmltopdf was the classic answer for years. Its GitHub repository is archived, and its last push was in November 2022. It uses an old WebKit engine, so modern CSS layout support is limited. I wouldn't start a new project on it. If you have one running, plan a move to headless Chrome.

html2canvas plus jsPDF builds the PDF in the browser by drawing the page into a canvas and placing that picture in the PDF. By construction, the result is an image of text: not searchable, not selectable, and not readable by a screen reader. It is fine for a quick visual export. For invoices and anything official, print with Chrome instead.

Before you run this on a server

If your app turns HTML into PDF on a server, the HTML often contains user input: a name, an address, a note. Headless Chrome will fetch anything that HTML points to, including file:// paths and internal addresses your server can reach but the user can't. That is server side request forgery by another route. What I'd do:

  • Escape every user value into the template. Never let a user supply a URL for Chrome to open.
  • Block requests you don't expect. In Playwright, page.route("**/*", ...) can abort anything that isn't your own assets.
  • Run the renderer somewhere without access to internal services or the cloud metadata endpoint.

The OWASP page on SSRF explains the wider problem.

Related tools and reading

To check an invoice template before printing, the HTML Beautifier makes a minified template readable. If the PDF goes to someone who needs to confirm it arrived unchanged, the Hash Generator gives its SHA-256 in your browser without uploading it.

Related reading: compressing PDFs with measured results, merging PDFs without uploading them, PDF optimization for web and email.