logo of Screenshot for Web
Free toolsPlaygroundDocsBlogPricing
LoginDashboard

Company

HomeFeaturesPricingBlogFacts

Screenshot Tools

Website ScreenshotsFull Page ScreenshotsScrolling ScreenshotsWebsite HistoryPDF Generation APIScreenshot API

Legal

Terms of UsePrivacy PolicyCookie PolicyCopyrightSecurity

Support

FAQSupportContact UsAPI Status
screen shot for web logo

No clutter. No distractions. Just clean, full-page screenshots with smart customization.

© 2026 HYDRANODE LTD. All rights reserved.

Screenshot for Web is operated by HYDRANODE LTD, a company registered in England and Wales, company number 15672526. Registered office: 124 City Road, London, London, England, EC1V 2NX.

FacebookInstagramLinkedInYouTube
  1. Home
  2. Blog
  3. Guides

HTML to PDF in JavaScript: page sizes, print CSS and page breaks, tested in Puppeteer

Turn HTML or a URL into a PDF with Puppeteer's page.pdf(). We ran every option that changes the output and show what each one really does.

Screenshot for Web·October 27, 2026·7 min read

Sources

  1. Puppeteer: Page.pdf() method
  2. Puppeteer: PDFOptions interface
  3. Chrome DevTools Protocol: Page.printToPDF
  4. Playwright: page.pdf()
  5. MDN: @page
  6. MDN: break-inside
  7. MDN: print-color-adjust

How this article was made

Researched and drafted with AI assistance from the sources listed. Every code sample was run, and every PDF in the figures was generated and measured, on 27 October 2026 with Puppeteer 25.16.0 (Chrome for Testing 156.0.8078.47) and Playwright 1.64.1 (Chromium 156.0.8078.4) on Node 22.21.1 on macOS. Page counts, sizes and fonts were read with poppler's pdfinfo, pdftotext and pdffonts.

Capture any page without ads, banners or chat widgets, free and without an account.

Try the free tools

More articles

  • News

    Puppeteer 25.19 stops print and dark mode emulation from cancelling each other

    Before Puppeteer 25.19.0, emulateMediaType and emulateMediaFeatures reset each other, losing print or dark mode. Our tests, the fix and a workaround.

    November 26, 2026
  • News

    Chrome 158 drops XSLT: what it does to screenshots of sitemaps and feeds

    We captured eight live sitemaps in Chrome 156 and Chromium 158. Styled pages turn into raw XML, a red warning bar is already in captures, and two fixes work.

    November 9, 2026
  • Research

    Chrome DevTools' full-size screenshot: where it fails on long and lazy pages

    We ran DevTools' full-size screenshot on six long pages: it stops at 16,384 pixels and misses content that appears on scroll. Here's why, and the fixes that worked.

    November 8, 2026

The quickest way to turn HTML or a URL into a PDF in JavaScript is headless Chrome: load the page with Puppeteer or Playwright, then call page.pdf(). It takes a few lines. Getting a PDF that looks right takes a little more, because the defaults are made for printing, not for keeping a page as it looks on screen.

We built a test report (a coloured banner, eight cards, a 60-row table and a box wider than any paper) and rendered it to PDF once per option. Below is the code we ran, what each option did to the output, and four behaviours that the documentation doesn't spell out.

Convert a URL to PDF

This is the whole script. We ran it against MDN's @page article.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://developer.mozilla.org/en-US/docs/Web/CSS/@page', {
    waitUntil: 'networkidle2',
  });
  await page.pdf({
    path: 'page.pdf',
    format: 'A4',
    printBackground: true,
    margin: { top: '15mm', bottom: '15mm', left: '12mm', right: '12mm' },
  });
  await browser.close();
})();

It produced a 9-page A4 PDF of about 1.6 MB. In a timed run of the same steps, loading the page took 1,576 ms and page.pdf() took 602 ms.

Convert an HTML string to PDF

For invoices and reports you usually have HTML, not a URL. Load it with page.setContent() instead of page.goto(). Without path, page.pdf() returns the file as bytes, ready to send in an HTTP response or upload.

const puppeteer = require('puppeteer');

const html = `<!doctype html>
<html><head><style>
  body { font-family: Helvetica, Arial, sans-serif; }
  h1 { background: #1d3a8a; color: #fff; padding: 12px; }
  .invoice-line { break-inside: avoid; }
</style></head>
<body>
  <h1>Invoice 1042</h1>
  <p class="invoice-line">3 × full-page captures ........ €0.03</p>
</body></html>`;

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setContent(html, { waitUntil: 'load' });
  const pdf = await page.pdf({
    format: 'A4',
    printBackground: true,
    margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' },
    displayHeaderFooter: true,
    headerTemplate: '<span></span>',
    footerTemplate: `<div style="font-size:9px; width:100%; text-align:center;">
      Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>`,
  });
  console.log('PDF bytes:', pdf.length);
  await browser.close();
})();

Output:

PDF bytes: 20906

What the defaults do

Puppeteer's page.pdf() sends Chrome's Page.printToPDF command. Calling it with no options gave us this:

SettingDefaultWhat we saw
PaperUS Letter612 × 792 pt pages
BackgroundsoffThe banner's blue background and the cards' tint were dropped
CSS mediaprintOur @media print rule hid the navigation bar
Margins0 in PuppeteerThe banner touched the top edge of the paper
Tagged PDFonpdfinfo reports Tagged: yes

Two of these are worth a closer look.

Backgrounds. With printBackground off, Chrome also adjusted the colours. The banner's white heading came out light grey (the darkest pixel was #ababab) so that it stays readable on white paper. MDN describes this as the browser's default economy colour mode. Add printBackground: true to keep backgrounds, as in the middle page of the figure at the top.

Margins. The protocol's own default margin is 1 cm on each side, but Puppeteer sends 0 for any margin you leave out (we read this in its parsePDFOptions source). So a bare page.pdf() prints edge to edge, while a tool that calls the protocol directly gets 1 cm margins.

To render with the screen stylesheet instead of the print one, call await page.emulateMediaType('screen') before page.pdf(). In our test that brought back the navigation bar that @media print hides.

Page size: format, width and height, or CSS @page

You can set the paper three ways: format (Letter, Legal, Tabloid, Ledger, A0 to A6), width and height with units, or an @page { size: ... } rule in the page's own CSS. format wins over width and height.

The CSS rule is where it gets surprising. We added @page { size: A5 landscape; margin: 10mm; } and asked for A4:

  • With preferCSSPageSize: true, we got A5 landscape pages, 595 × 420 pt, as the CSS asks.
  • With preferCSSPageSize left at false, we did not simply get A4. We got A4 landscape, and the content was laid out at A5 size and centred on it, with the same six page breaks as the A5 file. Chrome took the orientation from the CSS and ignored only the size.

Two PDF first pages from the same A5 landscape @page rule: with preferCSSPageSize false the content sits small and centred on a landscape A4 sheet; with true the page itself is A5 landscape.

The rule of thumb: if the page has an @page size, set preferCSSPageSize: true, or remove the rule. Mixing the two gives a page that matches neither.

Headers, footers and page numbers

displayHeaderFooter with headerTemplate and footerTemplate adds a header and footer on every page. Elements with the classes pageNumber, totalPages, date, title and url are filled in. Three things went wrong before we got it right:

  1. No margin, no room. The footer is drawn inside the page margin. With no bottom margin it was printed over our content.
  2. Tiny text. A footer without its own font-size came out 0.75 pt tall, too small to read. Set the size inline in the template.
  3. None of your styles. Page styles don't reach the templates (Playwright's documentation says so, and scripts in them don't run). Our footer was set in Times, while the page used Helvetica. Put every style inline.

Pass headerTemplate: '<span></span>' when you only want a footer. When we left it out, Chrome printed its default header, the date, time and page title, across the top of every page.

Three cropped page bottoms: a page-number footer printed over a card when there is no margin; the same footer sitting in a 20 mm bottom margin; and a footer with no font size that is a barely visible dot.

Chrome 156 also supports CSS page-margin boxes, which keep the footer in your stylesheet. This rule, with preferCSSPageSize: true and no header or footer options, printed "Page 1 of 3" to "Page 3 of 3" at 9 pt in the bottom margin:

@page {
  size: A4;
  margin: 20mm 15mm;
  @bottom-center {
    content: "Page " counter(page) " of " counter(pages);
    font-size: 9pt;
  }
}

Page breaks

Chrome breaks pages wherever the paper runs out unless CSS says otherwise. On Letter paper our sixth card was cut across pages 1 and 2. Adding break-inside: avoid to the cards moved the whole card to page 2.

Bottom of page 1 and top of page 2, joined by a red line: by default card 6 is split across the break; with break-inside avoid the card starts whole on page 2.

The properties you need:

  • break-inside: avoid keeps a card, figure, table row or invoice line on one page.
  • break-before: page and break-after: page force a new page, for example before each chapter.
  • page-break-inside: avoid is the older name for break-inside: avoid, and browsers still accept it as an alias.

Tables need less work than you may expect. Our table started on page 2 and ran onto page 3, and Chrome repeated its <thead> row at the very top of page 3 without any extra CSS.

Wide content is shrunk, then cut off

Pages built for a wide screen often don't fit on paper. Chrome shrinks the whole page to fit, but only up to a point. We widened one box step by step and measured the body text, which is 12 pt at full size:

Widest boxPagesBody text
700 px412.00 pt
900 px310.06 pt
1,100 px38.31 pt
1,400 px38.00 pt
2,000 px38.00 pt
3,000 px38.00 pt

Shrinking stops at two thirds of full size. Anything wider is cut off: a marker at the right end of the 3,000 px box was missing from the PDF entirely, both in the rendered page and in its text. The scale option (0.1 to 2) shrinks further if you need it, but the better fix is print CSS that lets wide elements wrap, for example max-width: 100% on images and tables.

Keeping colours without printBackground

If you want some backgrounds but not all, use print-color-adjust: exact in CSS instead of printBackground. We tried it without printBackground:

  • on the banner, unprefixed or as -webkit-print-color-adjust, it kept the banner blue and nothing else;
  • on the html element, it kept every background, because the property is inherited.

Playwright works the same way

Playwright's page.pdf(), run on Chromium, takes the same options under the same names:

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.pdf({ path: 'example.pdf', format: 'A4', printBackground: true });
  await browser.close();
})();

Rendered with no options, our test report came out the same as Puppeteer's: Letter paper, no margins, no backgrounds. Rasterised at 72 dpi, all three pages matched pixel for pixel. One small difference: Playwright's A4 page measured 595.92 × 842.88 pt against Puppeteer's 595.92 × 841.92 pt, a third of a millimetre taller. For screen styles in Playwright, call page.emulateMedia({ media: 'screen' }).

A checklist for good PDFs

  1. Set format (or @page size with preferCSSPageSize: true); never rely on the Letter default.
  2. Add printBackground: true, or print-color-adjust: exact where colour matters.
  3. Give margins. Make the top or bottom margin tall enough for any header or footer.
  4. Style header and footer templates inline, with an explicit font-size.
  5. Add break-inside: avoid to anything that shouldn't be split.
  6. Check wide layouts: past two-thirds shrink, Chrome cuts content off.
  7. Wait for the page to finish loading before page.pdf(). Puppeteer waits for web fonts by default (waitForFonts), but not for late images or data.

If what you need is an image of the page rather than a PDF, our free screenshot tool captures full pages as PNG, JPEG or WebP.