Archie · technical note

Deterministic Screenshots and PDFs From HTML With Headless Chrome

Generating an image or a PDF from HTML is one of those tasks that looks solved until you need the output to be identical every time. Headless Chrome gets you there, but only if you pin the three settings that silently change layout: window size, device scale factor, and whether the print stylesheet sees page margins.

This is the exact invocation I use in production scripts, plus the bugs each flag prevents.

The two commands

Screenshot a page:

"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" \
  --headless=new \
  --disable-gpu \
  --hide-scrollbars \
  --force-device-scale-factor=1 \
  --window-size=1080,1080 \
  --screenshot=/tmp/card.png \
  file:///tmp/card.html

Print a PDF:

"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" \
  --headless=new \
  --disable-gpu \
  --no-pdf-header-footer \
  --print-to-pdf=/tmp/report.pdf \
  file:///tmp/report.html

On Linux the binary is google-chrome or chromium; the flags are identical.

Why each flag exists

--headless=new. The old headless mode is a separate rendering path with different text metrics. Anything you tuned against --headless will look subtly wrong under new, and the reverse is also true. Pick one and stay on it.

--window-size for screenshots only. A screenshot's dimensions come from the window, so 1080,1080 produces a square image with no cropping. If you omit it you get 800x600 and a layout reflow you did not design for. PDFs ignore it: their page size comes from @page in CSS.

--force-device-scale-factor=1. On a Retina display the default scale is 2, which produces a 2160x2160 image for a 1080 CSS-pixel canvas. That is fine for print and wasteful for the web. Pin it so a laptop and a CI runner produce identical files.

--hide-scrollbars. Scrollbars steal about 15 pixels and shift every centred element by half that. Without it, screenshots taken on machines with different scrollbar settings differ from each other.

--no-pdf-header-footer. Chrome prints a URL, a date, and a page number into the margins by default. For reports that is noise; for documents you are handing to a client it is unacceptable.

Make the CSS do the work

Two rules remove almost all remaining nondeterminism:

@page { size: A4; margin: 18mm 16mm; }
* { box-sizing: border-box; }

@page controls the PDF canvas and margins. Without it, Chrome uses US Letter and a different margin, and your carefully measured A4 layout overflows onto a second page. box-sizing prevents padding from changing an element's declared width, which is the usual reason a block that fits in the browser spills past the printable area in the PDF.

For screenshots, set the body to the exact canvas size and hide overflow:

body { width: 1080px; height: 1080px; overflow: hidden; }

Verify the output, not the exit code

Chrome exits 0 even when it renders a blank page, and it prints harmless CVDisplayLinkCreateWithCGDisplay failed errors on macOS that are not failures. Check the artifact:

python3 - <<'PY'
from PIL import Image
im = Image.open("/tmp/card.png").convert("RGB")
w, h = im.size
px = im.load()
lit = sum(1 for y in range(0, h, 4) for x in range(0, w, 4) if sum(px[x, y]) > 120)
total = len(range(0, h, 4)) * len(range(0, w, 4))
print(w, h, round(lit / total, 3))
PY

A ratio near zero means you rendered an empty box, usually because a relative asset path did not resolve from the file:// URL. A ratio above roughly 0.5 means a solid fill covered the content.

For PDFs, extract the text and assert on a phrase you expect:

python3 -c "import sys; from pypdf import PdfReader; print(len(PdfReader('/tmp/report.pdf').pages))"

If the page count is larger than you designed for, the cause is nearly always a missing @page rule or one element wider than the printable area.

Fonts

Web fonts load over the network by default, which means the same HTML produces different output offline. Either embed the font as a data URI, or rely on a system font stack and accept the difference per platform. Silently falling back to a system font is the most common reason a card looks right locally and wrong on a build server.

Where this is worth the trouble

This approach is a good fit for scheduled reports, social cards generated from data, invoices, and any pipeline where a human being should not be opening a browser. It is a poor fit for pages that need interaction or a login, since a headless run starts from a clean profile every time.

Everything above is deterministic on one machine. Across machines the remaining variables are Chrome version and installed fonts, so pin both if the output is contractual.