Puppeteer HTML to PDF: The Complete Guide (Headers, Page Breaks, Fonts, Lambda)

Puppeteer is a Node.js library that controls headless Chrome or Chromium, and its page.pdf() method is one of the most common ways to turn HTML into a PDF: Chrome renders the page, then prints it.

This guide covers what you need for production PDFs with Puppeteer: converting HTML and URLs, the page.pdf() options, headers and footers, page breaks, fonts, sending the file as a download, speed, file size and AWS Lambda.

Every example was run with Puppeteer 25.18 on Node.js 24 in November 2026. They use ES modules (import), so save them as .mjs files or set "type": "module" in your package.json.

1. Generate a PDF from HTML with Puppeteer

Install Puppeteer. It downloads a compatible version of Chrome during installation:

npm install puppeteer

Then load your HTML into a page and print it:

import puppeteer from 'puppeteer';

const html = `
  <html>
    <head>
      <style>
        body { font-family: sans-serif; }
        h1 { color: #2563eb; }
      </style>
    </head>
    <body>
      <h1>Invoice INV-1001</h1>
      <p>Total: $250.00</p>
    </body>
  </html>`;

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle0' });
await page.pdf({ path: 'invoice.pdf', format: 'A4', printBackground: true });
await browser.close();

setContent loads the HTML string, and waitUntil: 'networkidle0' waits until any images, stylesheets and fonts it links to have loaded. printBackground: true keeps background colours and images, which Chrome leaves out by default.

2. Convert a URL to PDF

To convert a web page, open it with page.goto instead:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://en.wikipedia.org/wiki/PDF', { waitUntil: 'networkidle0' });

// Optional: print the page as it looks on screen, not with its print stylesheet
await page.emulateMediaType('screen');

await page.pdf({
  path: 'webpage.pdf',
  format: 'A4',
  printBackground: true,
  margin: { top: '20mm', bottom: '20mm', left: '10mm', right: '10mm' },
});
await browser.close();

The waitUntil option decides when the page counts as loaded:

  • load (the default) waits for the page’s load event.
  • domcontentloaded waits only for the HTML to be parsed, which is faster but may miss images.
  • networkidle0 waits until there have been no network connections for 500 ms.
  • networkidle2 waits until there have been no more than two connections for 500 ms, which suits pages that keep a connection open.

page.pdf() uses the page’s print stylesheet (@media print), so a site may hide its navigation or change its layout in the PDF. emulateMediaType('screen') prints the page as it looks on screen instead.

Pages that lazy-load images

Many pages only load images when they scroll into view, so they are missing from the PDF. Scroll through the page before printing:

// Scroll one screen at a time so lazy-loaded images start loading
await page.evaluate(async () => {
  for (let y = 0; y < document.body.scrollHeight; y += window.innerHeight) {
    window.scrollTo(0, y);
    await new Promise((resolve) => setTimeout(resolve, 200));
  }
  window.scrollTo(0, 0);
});
await page.waitForNetworkIdle();

Wait for your own ready signal

If your page draws charts or fetches data with JavaScript, have it set a flag when it is finished, for example window.readyForPdf = true, and wait for that flag before printing:

await page.waitForFunction('window.readyForPdf === true');

3. page.pdf() Options

These are the options page.pdf() accepts, with their defaults:

OptionWhat it doesDefault
pathFile to save the PDF to. Without it, use the returned bytes.Not saved
formatPaper size: Letter, Legal, Tabloid, Ledger, A0 to A6Letter
width, heightA custom paper size, such as '210mm'None
landscapeLandscape orientationfalse
margin{ top, right, bottom, left }, such as '20mm'None
printBackgroundPrint background colours and imagesfalse
scaleZoom the content, from 0.1 to 21
pageRangesPages to include, such as '1-3, 5'All pages
preferCSSPageSizeUse the CSS @page size instead of formatfalse
displayHeaderFooter, headerTemplate, footerTemplateHeader and footer on every page (see the next section)Off
omitBackgroundTransparent page background instead of whitefalse
outlineAdd bookmarks built from the page's headingsfalse
taggedCreate a tagged (accessible) PDFtrue
waitForFontsWait for web fonts to load before printingtrue
timeoutMilliseconds to wait before giving up30000

page.pdf() returns the PDF as a Uint8Array. Since Puppeteer 22 that is no longer a Node.js Buffer, which matters when you send it over HTTP (see section 7).

4. Headers, Footers and Page Numbers

Set displayHeaderFooter: true and give Chrome an HTML template for each:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(`<title>Monthly report</title>` + '<p>Lorem ipsum dolor sit amet.</p>'.repeat(120));

await page.pdf({
  path: 'report.pdf',
  format: 'A4',
  displayHeaderFooter: true,
  headerTemplate: `
    <div style="font-size: 9px; width: 100%; text-align: center;">
      <span class="title"></span>
    </div>`,
  footerTemplate: `
    <div style="font-size: 9px; width: 100%; text-align: center;">
      Page <span class="pageNumber"></span> of <span class="totalPages"></span>
    </div>`,
  // The header and footer print inside the margins, so leave room for them
  margin: { top: '25mm', bottom: '20mm', left: '15mm', right: '15mm' },
});
await browser.close();

The rules for header and footer templates:

  • They print inside the top and bottom margins, so set margins large enough to hold them.
  • Chrome fills in elements with these classes: date, title, url, pageNumber and totalPages.
  • The templates don’t inherit the page’s CSS, so set the font size and styles inline.
  • They can’t use the page’s web fonts. In our test, a footer that named the page’s Google font fell back to a system font, and adding the font’s <link> to the template made page.pdf() time out after 30 seconds. Use fonts installed on the machine, and embed images as data: URIs, which do render.
  • If you set only one of the two templates, Chrome prints its default for the other: the date and title at the top, or the URL and page number at the bottom. Pass '<span></span>' to leave one empty.
  • Background colours in a header or footer only print with -webkit-print-color-adjust: exact in the template’s style. Without it, ours came out blank.

Chrome uses the same templates on every page, and CSS can’t change that: in our tests, @page :first { margin-bottom: 0; } still printed the footer on page 1. Instead, print the first page and the rest separately, then merge them with pdf-lib (npm install pdf-lib):

import { writeFile } from 'node:fs/promises';
import puppeteer from 'puppeteer';
import { PDFDocument } from 'pdf-lib';

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent('<h1>Cover page</h1><div style="break-before: page"></div>' + '<p>Lorem ipsum dolor sit amet.</p>'.repeat(120));

const options = { format: 'A4', margin: { top: '20mm', bottom: '20mm' } };
const footerTemplate = `
  <div style="font-size: 9px; width: 100%; text-align: center;">
    Page <span class="pageNumber"></span> of <span class="totalPages"></span>
  </div>`;

// Page 1 without a footer, then the rest with one
const cover = await page.pdf({ ...options, pageRanges: '1' });
const rest = await page.pdf({
  ...options,
  pageRanges: '2-',
  displayHeaderFooter: true,
  headerTemplate: '<span></span>',
  footerTemplate,
});
await browser.close();

const merged = await PDFDocument.create();
for (const bytes of [cover, rest]) {
  const doc = await PDFDocument.load(bytes);
  const pages = await merged.copyPages(doc, doc.getPageIndices());
  pages.forEach((p) => merged.addPage(p));
}
await writeFile('report.pdf', await merged.save());

The page numbers stay correct: Chrome numbers pages within the whole document, so the footer on the second page reads “Page 2 of 6”.

5. Page Breaks

Chrome follows the CSS fragmentation properties:

@page { size: A4; margin: 20mm; }

.page-break { break-before: page; }        /* start a new page here */
tr, figure, .card { break-inside: avoid; }  /* don't split these across pages */
  • The older page-break-before and page-break-inside properties work too.
  • A table’s <thead> repeats at the top of every page automatically.
  • Chrome ignores the @page size unless you pass preferCSSPageSize: true to page.pdf(). With it, an @page { size: A5; } rule produced A5 pages in our test.

6. Fonts and Emoji

Web fonts work as they do in the browser, from @font-face or a Google Fonts link, and page.pdf() waits for them to load by default. That includes emoji:

<head>
  <link href="https://fonts.googleapis.com/css2?family=Noto+Color+Emoji&display=swap" rel="stylesheet">
  <style>
    body { font-family: sans-serif, 'Noto Color Emoji'; }
  </style>
</head>
<body>
  <p>Hello 😀 📄 ✅</p>
</body>

Header and footer templates can’t load web fonts, so they use the fonts installed on the machine. That is where servers cause trouble: a Linux server or AWS Lambda often has very few fonts, and characters it has no font for print as empty boxes. Install the fonts you need on the server, or ship them with your code and point fontconfig at them:

process.env.FONTCONFIG_FILE = '/var/task/fonts.conf';
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
  <dir>/var/task/fonts/</dir>
  <cachedir>/tmp/fonts-cache/</cachedir>
</fontconfig>

7. Send the PDF as a Download

In a web app, generate the PDF in memory and send it with a Content-Disposition: attachment header. This Express server keeps one browser open for every request:

import express from 'express';
import puppeteer from 'puppeteer';

const app = express();
const browser = await puppeteer.launch(); // one browser, reused for every request

app.get('/invoice.pdf', async (req, res) => {
  const page = await browser.newPage();
  try {
    await page.setContent('<h1>Invoice INV-1001</h1><p>Total: $250.00</p>');
    const pdf = await page.pdf({ format: 'A4', printBackground: true });

    res.set({
      'Content-Type': 'application/pdf',
      'Content-Disposition': 'attachment; filename="invoice.pdf"',
    });
    res.send(Buffer.from(pdf)); // page.pdf() returns a Uint8Array, not a Buffer
  } finally {
    await page.close();
  }
});

app.listen(3000);

Don’t skip Buffer.from(). page.pdf() returns a Uint8Array, and Express 4 sends a raw Uint8Array as JSON ({"0":37,"1":80,...}), which arrives as a broken file. Express 5 handles either.

Save a PDF from a URL

If the PDF already exists and you only want to save it, you don’t need Puppeteer to render anything. Download it directly:

import { writeFile } from 'node:fs/promises';

const res = await fetch('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf');
if (!res.ok) throw new Error(`Download failed: ${res.status}`);
await writeFile('dummy.pdf', Buffer.from(await res.arrayBuffer()));

8. Generate PDFs Faster

  • Reuse one browser. In our tests, launching Chrome took 310 to 430 ms, while a simple PDF on a browser that was already running took 46 to 84 ms. Launch once, open a new page per PDF, and close the page when you are done, as the Express example does.
  • Wait only as long as you need. For an HTML string with no remote files, the default load is enough. Use networkidle0, or your own ready signal, only when the page fetches data or images.
  • Reuse downloaded files. Passing userDataDir: './tmp' to puppeteer.launch() keeps Chrome’s cache between runs, so the same images, stylesheets and fonts aren’t downloaded again.
  • In Docker, add --disable-dev-shm-usage to the launch args. Docker’s small /dev/shm can crash Chrome on large pages. The Puppeteer troubleshooting guide covers this and other environment problems.

9. Make PDFs Smaller with Ghostscript

Puppeteer embeds images at their full resolution, so PDFs of image-heavy pages get large. Ghostscript (gs) can rewrite the file with smaller images:

import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

const run = promisify(execFile);

// Rewrite the PDF with Ghostscript, downsampling images to 150 dpi (/screen is 72 dpi)
await run('gs', [
  '-sDEVICE=pdfwrite', '-dNOPAUSE', '-dQUIET', '-dBATCH',
  '-dPDFSETTINGS=/ebook',
  '-sOutputFile=webpage-small.pdf',
  'webpage.pdf',
]);

On a 28-page Wikipedia article, this took the PDF from 1.49 MB to 0.54 MB. /screen makes files smaller still, and /printer keeps more detail. Ghostscript has to be installed on the server; the Ghostscript documentation lists every option.

10. Puppeteer on AWS Lambda

The Chrome that the full puppeteer package downloads is too large for a zip-packaged Lambda function and needs system libraries the Lambda runtime doesn’t include. Use puppeteer-core with @sparticuz/chromium, a Chromium build made for Lambda. (chrome-aws-lambda, which older guides use, is no longer maintained.)

import chromium from '@sparticuz/chromium';
import puppeteer from 'puppeteer-core';

export const handler = async (event) => {
  const browser = await puppeteer.launch({
    args: await puppeteer.defaultArgs({ args: chromium.args, headless: 'shell' }),
    executablePath: await chromium.executablePath(),
    headless: 'shell',
  });
  try {
    const page = await browser.newPage();
    await page.setContent(event.html, { waitUntil: 'networkidle0' });
    const pdf = await page.pdf({ format: 'A4', printBackground: true });
    return {
      statusCode: 200,
      headers: { 'Content-Type': 'application/pdf' },
      isBase64Encoded: true,
      body: Buffer.from(pdf).toString('base64'),
    };
  } finally {
    await browser.close();
  }
};

The launch options follow the @sparticuz/chromium README. Install the puppeteer-core version that supports the same Chromium version as your @sparticuz/chromium release; the package’s README explains how to match them. Our HTML to PDF on AWS Lambda guide walks through the whole deployment, from packaging to API Gateway, and covers cold starts and memory limits.

FAQ

Why is my Puppeteer PDF missing background colours?

Chrome leaves backgrounds out of PDFs by default. Pass printBackground: true to page.pdf(). For backgrounds inside a header or footer template, also add -webkit-print-color-adjust: exact to the template’s style.

Why does the PDF look different from the page in my browser?

page.pdf() uses the page’s print stylesheet, and many sites hide or rearrange content for printing. Call await page.emulateMediaType('screen') before page.pdf() to print the on-screen version.

How do I add page numbers to a Puppeteer PDF?

Set displayHeaderFooter: true and put <span class="pageNumber"></span> and <span class="totalPages"></span> in your footerTemplate. Give the page a bottom margin large enough for the footer.

Why does page.pdf() return a Uint8Array instead of a Buffer?

Since Puppeteer 22, page.pdf() returns a Uint8Array. Wrap it in Buffer.from(pdf) before passing it to APIs that expect a Buffer, such as Express 4’s res.send().

Can Puppeteer convert HTML to PDF without Chrome?

No. Puppeteer only controls a browser, and the browser does the rendering. If you don’t want to run Chrome on your own servers, a hosted HTML to PDF API does the same job.

Conclusion

Puppeteer turns any HTML that Chrome can render into a PDF, and the options above cover what production documents need: page sizes and margins, headers and footers with page numbers, page breaks, fonts and smaller files. The work that remains is running Chrome yourself: keeping a browser alive, managing memory, and packaging it for servers and Lambda.

APITemplate.io offers a PDF generation API and an HTML to PDF API that render with Chromium, so you can send HTML or a template and get a PDF back without hosting a browser. If you are using Puppeteer and hosting the services yourself, you may register an account and try out our API services.