Use Playwright's page.pdf(). It loads your HTML in Chromium, applies print CSS, and saves a PDF. Install with npm install playwright, then run npx playwright install chromium to download the browser. Current Playwright releases need Node 20 or newer.
import { chromium } from 'playwright';
const html = '<h1>Invoice 1042</h1><p style="background:#eef">Total due: $480.00</p>';
const browser = await chromium.launch();
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle' });
await page.pdf({
path: 'invoice.pdf',
format: 'A4',
printBackground: true,
margin: { top: '20mm', right: '15mm', bottom: '20mm', 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>',
});
await browser.close();What the options do
format: 'A4' sets the paper size (the default is Letter). margin defaults to none, so set it yourself and leave enough top and bottom room for the header and footer. printBackground defaults to false, which is why background colors and images vanish from the PDF until you turn it on.
displayHeaderFooter also defaults to false. Once it is on, headerTemplate and footerTemplate take HTML, and Playwright fills in elements with the classes pageNumber, totalPages, date, title and url. The snippet above only needs a footer, so the header is an empty div.
Caveats
Header and footer templates are rendered separately from your page. Script tags inside them are not evaluated and your page styles are not visible, so inline the styles and set the font size in the template itself.
page.pdf() uses the print CSS media type. If you want the PDF to look like the on-screen page, call await page.emulateMedia({ media: 'screen' }) before it. And if your CSS declares an @page size, pass preferCSSPageSize: true so it takes priority over format; the default is false.
