I maintain a small set of printable test pages (colour, black and white, nozzle check, alignment). Each one has to ship as an A4 PDF and a US Letter PDF, and they all have to print at true size. Keeping two hand-made copies of every page in sync got old fast, so I moved to a single HTML source per page and generate both PDFs from it. Here's the setup and the things that bit me.
One source, two paper sizes
Each page is plain HTML plus one print stylesheet. The paper size isn't hard-coded in the page. It comes from a single custom property and a named @page rule:
:root { --sheet-w: 210mm; --sheet-h: 297mm; } /* A4 default */ :root[data-paper="letter"] { --sheet-w: 8.5in; --sheet-h: 11in; } @page a4 { size: A4; margin: 0; } @page letter { size: letter; margin: 0; } .sheet { page: a4; width: var(--sheet-w); height: var(--sheet-h); } :root[data-paper="letter"] .sheet { page: letter; } Flip data-paper on the root element and the same markup lays out for the other size.
Generating the PDFs
Headless Chromium does the rendering. The two settings that matter are preferCSSPageSize (so @page wins over the script's defaults) and scale: 1:
import { chromium } from 'playwright'; const browser = await chromium.launch(); const page = await browser.newPage(); for (const paper of ['a4', 'letter']) { await page.goto(`file://${process.cwd()}/alignment.html`); await page.evaluate(p => document.documentElement.dataset.paper = p, paper); await page.pdf({ path: `dist/alignment-${paper}.pdf`, preferCSSPageSize: true, printBackground: true, scale: 1, }); } await browser.close(); Things that went wrong first
- Margins sneaking back in. Without
margin: 0in@page, Chromium adds its own default margin, and a full-bleed grid gets shrunk to fit. - Background colours vanishing. Colour blocks are backgrounds, so
printBackground: trueis required. On the web version, addprint-color-adjust: exacttoo. - Fit-to-page in the user's viewer. You can't control this, but you can detect it. I put a 100 mm ruler on every sheet so anyone can check the scale with a real ruler.
- Hairlines disappearing. Lines thinner than about 0.25 pt can drop out on some laser drivers. I settled on 0.3 pt for the finest nozzle-check lines.
- Fonts. System fonts differ between machines. Self-host one font and
await document.fonts.readybefore printing.
Testing the output
I check every generated PDF by printing it on both an inkjet and a laser printer, then measuring the ruler and border. If a sheet passes on paper, it passes.
You can see the finished pages, all generated this way, at PrinterPrintTest.com's free printer test pages. The alignment grid, for example, is here. The bare-bones HTML and CSS version is open source as printer-test-page-kit.
If you've fought @page in Firefox or Safari, I'd like to hear what worked for you. Named pages there are still patchy.
