DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk7 min

Tips for Generating PDFs with Puppeteer

A practical guide to Puppeteer’s page.pdf(), including print styling, page dimensions, readiness checks, browser compatibility, and troubleshooting.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Puppeteer’s page.pdf() method after navigating to the page, and deliberately set print media, paper size, margins, background handling, and a readiness condition. A successful navigation alone does not guarantee that an application’s asynchronous content has rendered.

Generate a PDF with Puppeteer

Puppeteer documents Page.pdf() as its method for printing a page to PDF. It returns a Uint8Array; use Page.createPDFStream() instead when you need a readable stream. See the PDF generation guide and the Page.pdf() API reference.

Runnable example

Install Puppeteer in your project with npm install puppeteer, then save this as make-pdf.js and run node make-pdf.js. The example waits for navigation to reach networkidle2, then writes the PDF bytes to a file.

const puppeteer = require('puppeteer');
const fs = require('node:fs/promises');

(async () => {
  const browser = await puppeteer.launch();
  try {
    const page = await browser.newPage();
    await page.goto('https://example.com', { waitUntil: 'networkidle2' });
    const pdf = await page.pdf({ path: 'page.pdf' });
    // page.pdf() returns a Uint8Array; path also writes the file.
    console.log(`Wrote ${pdf.length} bytes to page.pdf`);
  } finally {
    await browser.close();
  }
})();

Replace the URL and output path for your task. If a site’s application fetches or renders data after navigation, add a wait for that site’s own readiness signal before calling page.pdf(); network idleness is not proof that app-specific work is complete.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose what the PDF should look like

Puppeteer renders PDFs using the browser’s print CSS media type by default. That means rules inside @media print can change or hide content compared with a screen screenshot. If the PDF should reflect screen styles, call page.emulateMediaType('screen') before generating it. The choice is between a print-oriented document and a rendering styled for the screen, not simply two output file formats. See the PDF guide.

Paper size, orientation, and margins

The current surfaced PDFOptions API reference documents Letter as the default format and no margins by default. Set margins and a paper format explicitly when the output must meet a known page layout. format takes priority over width and height; use landscape: true for landscape orientation.

await page.pdf({
  path: 'report.pdf',
  format: 'A4',
  landscape: false,
  margin: {
    top: '18mm',
    right: '16mm',
    bottom: '18mm',
    left: '16mm'
  }
});

If your document defines its intended page size in CSS with @page, set preferCSSPageSize: true so that CSS page sizing takes priority over the API’s format or dimensions. Its default is false, in which case content is scaled to fit the selected paper size.

await page.pdf({
  path: 'css-sized-report.pdf',
  preferCSSPageSize: true
});

Use pageRanges to select pages; an empty string means all pages. The API documents scale as a value from 0.1 to 2, with 1 as the default. Adjust it only when you understand the layout trade-off: scaling can change the size of text and other content on the page.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Backgrounds and print colors

Background graphics are omitted by default because printBackground defaults to false. Enable it when a background color or image is part of the document’s intended appearance:

await page.pdf({ path: 'colored.pdf', printBackground: true });

Print output may also use modified colors by default. To request exact CSS colors for printing, apply -webkit-print-color-adjust: exact in your stylesheet, for example in a print rule:

@media print {
  html {
    -webkit-print-color-adjust: exact;
  }
}

Whether exact color adjustment is appropriate depends on the output: preserving screen-like colors can use more ink or reduce contrast for paper. The PDF guide and API describe these print behaviors and options: PDF generation and PDFOptions.

Headers, footers, and transparency

Set displayHeaderFooter: true to use header and footer templates. Templates can include injected date, title, URL, page number, and total-page values. omitBackground can omit the default white background to allow transparency. The surfaced API marks tagged and outline experimental, so confirm their behavior against the Puppeteer version you deploy before relying on them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wait for the page that should be printed

The example’s waitUntil: 'networkidle2' is a navigation strategy, not a universal application-ready test. A page can still be rendering after network activity settles, or have long-running requests that make a network-idle condition unsuitable. Wait for a selector, state, or other signal that means the required content is present.

Wait for an application-specific selector

If the site exposes a stable element after its report has loaded, wait for it explicitly:

await page.goto('https://example.com/report', { waitUntil: 'domcontentloaded' });
await page.waitForSelector('[data-report-ready="true"]');
await page.pdf({ path: 'report.pdf', format: 'A4' });

Replace the sample selector with an element the target application actually renders when its content is ready. If you do not control the site, inspect its page and choose a selector that is stable across the versions you need to support.

Fonts and other late-loading content

PDFOptions.waitForFonts defaults to true, so Puppeteer waits for fonts before creating the PDF. The API notes that waiting for fonts may require bringing a background page to the front. Font waiting does not replace application-specific readiness checks for data, images, or client-rendered components. Consult the PDFOptions reference and Page.pdf() reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PDF options at a glance

These defaults and behaviors are documented in the Puppeteer PDFOptions reference surfaced as version 25.12.0. Check the documentation for the version installed in your project, especially before depending on experimental options.

Option Documented behavior When to set it
format Defaults to Letter; takes priority over width and height. Use a named paper size such as A4 or Letter.
width and height Used for page dimensions unless format takes priority. Use when you need custom dimensions rather than a named format.
landscape Defaults to false. Set true for landscape pages.
margin Defaults to no margins. Set page padding for print layout or binding.
preferCSSPageSize Defaults to false; when true, CSS @page sizing takes priority. Use when page dimensions are controlled by the document stylesheet.
printBackground Defaults to false. Enable if backgrounds must appear in the PDF.
pageRanges An empty string means all pages. Restrict output to selected pages.
scale Defaults to 1; allowed range is 0.1 to 2. Adjust content scale when necessary, accounting for its effect on layout.
displayHeaderFooter Defaults to false. Enable templates for printed headers and footers.
waitForFonts Defaults to true. Keep font readiness enabled unless your workflow has a specific reason to change it.
timeout Defaults to 30,000 ms; 0 disables the timeout. Set deliberately for slow documents; disabling it removes the PDF-generation timeout.
omitBackground Can omit the default white background to allow transparency. Use when transparent output is intended.
tagged and outline Marked experimental in the surfaced API reference. Verify support and behavior in the version you run.

Keep browser and Puppeteer versions reproducible

Puppeteer guarantees compatibility with its bundled browser. Launch options support a custom executablePath and Chrome channel, but the launch reference says a custom executable is used at the developer’s risk. For repeatable PDF output, keep a consistent Puppeteer/browser pairing and record the versions used in deployment documentation. See the launch options reference.

Troubleshoot common PDF problems

  • Content is missing or incomplete: Navigation may have finished before the application rendered its data. Wait for a page-specific selector or readiness condition before calling page.pdf().
  • The PDF layout differs from the browser: PDF generation uses print media by default. Check the site’s print CSS, or call page.emulateMediaType('screen') before generating the PDF if screen styles are intended.
  • Background colors or images are absent: Set printBackground: true. If colors still differ, print color adjustment may be changing them; consider -webkit-print-color-adjust: exact.
  • Paper size or content scaling is unexpected: Check whether format overrides your width and height, whether preferCSSPageSize should be enabled for CSS @page, and whether the selected margins or scale are affecting fit.
  • Fonts are wrong or incomplete: Puppeteer waits for fonts by default, but late application content may still need an explicit readiness wait. If the page is in the background, the API notes font waiting may require bringing it to the front.
  • PDF creation times out: The documented default PDF timeout is 30,000 ms. Set a suitable timeout for the document; 0 disables this timeout, so use it only if your calling process has another way to prevent work from hanging.
  • Output changes after a deployment: Check the Puppeteer and browser versions. Compatibility is guaranteed with Puppeteer’s bundled browser, not arbitrary custom executables.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you only need a PDF of a URL, ScreenshotNeo provides a one-request screenshot API that can return a PDF. Its PDF options include paper size, margins, landscape, and page ranges. This is a separate service rather than Puppeteer code; see the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -d format=pdf -o page.pdf

With ScreenshotNeo, cookie banners are accepted and removed before capture, alongside known newsletter popups and chat widgets; each cleanup step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server offers screenshot and PDF tools for AI agents. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sign up free for 1,000 screenshots a month with no card.

Frequently Asked Questions

Can Puppeteer stream a PDF instead of returning it as bytes?

Yes. Use Page.createPDFStream() when you need a readable stream; Page.pdf() returns a Uint8Array.

What is Puppeteer’s default PDF timeout?

The surfaced PDFOptions reference documents a default of 30,000 ms; setting timeout to 0 disables that timeout.

Does Puppeteer work with any installed Chrome version?

Its compatibility guarantee covers its bundled browser. A custom executable path is supported at the developer’s risk.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.