You can turn any HTML page into a print-ready PDF with headless Chrome and about 60 lines of Node.js 22, with no Puppeteer and no npm packages: start Chrome with a debugging port, connect to its WebSocket, and send two DevTools Protocol commands, Page.navigate and Page.printToPDF.
We ran the script exactly as published on 12 November 2026 against Chrome 136. It took 4.6 seconds end to end, most of it Chrome starting and a fixed wait after navigation. preferCSSPageSize is the switch that makes @page { size: A4 } work: with it the PDF measured 594.96 by 841.92 points (A4), without it 612 by 792 (US Letter).
Four things go wrong most often: fonts print as the fallback unless you wait on document.fonts.ready; pages print on Letter without preferCSSPageSize; content that fades in stays hidden, because headless Chrome reports reduced motion; and deleting the temporary profile can fail with ENOTEMPTY while Chrome is still being killed.
The whole script, the CSS and the fixes: HTML to PDF with headless Chrome in Node.js, no Puppeteer
Top comments (2)
Skipping Puppeteer when Chrome is already on the host saves a lot of install weight, especially in CI or small build scripts.
A couple of CDP details worth watching as this scales up:
await sleep(1500)afterPage.navigatecan still race if a chart or local asset loads slowly. SincePage.enableis already called, listening forPage.loadEventFiredbefore checkingdocument.fonts.readyanddocument.imageskeeps output deterministic without padding every run by 1.5 seconds.Page.printToPDFalso switches Blink into@media printmode by default. Even withprintBackground: true, screen-only layout rules or CSS variables can vanish unless you callEmulation.setEmulatedMediawithmedia: "screen"or mirror them in print rules.For the
ENOTEMPTYcleanup snag, sendingBrowser.closeover the WebSocket and waiting for the child processexitevent beforermSyncprevents stale profile folders from piling up inos.tmpdir().Driving printToPDF straight over CDP instead of pulling in Puppeteer is a lean choice for a build script that only renders a handful of documents — one bundled Chrome, a WebSocket, and two protocol commands, with nothing to keep patched. The 'same HTML renders the PDF, the image, and the on-screen page' point matters for consistency, because any divergence between preview and exported artifact usually comes from print-only CSS that isn't exercised in the browser view. This maps cleanly onto Electron too: the renderer already ships Chromium, so the same print path can reuse the app's bundled engine instead of spawning a separate headless binary, and a temp profile per job keeps state from leaking between documents.