October 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 NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Chromium

Best Practices for Generating PDFs with Puppeteer

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 page.pdf() only after the page is genuinely ready, and treat the result as a print document. Set the paper contract explicitly—format, margins, orientation, scale, colors, backgrounds and page ranges—then verify fonts, dynamic data and the browser build you deploy. Puppeteer renders print media by default, so a screen-perfect page can still produce an unexpected PDF unless you deliberately choose the media type and print CSS.

A reliable Puppeteer PDF workflow

The basic sequence is straightforward: launch Puppeteer, open a page, wait for an application-specific ready condition, and call page.pdf(). Navigation finishing does not necessarily mean that charts, images or client-rendered data are complete.

  1. Launch Puppeteer and create a page.
  2. Navigate with a timeout and a readiness strategy appropriate to the application.
  3. Choose print or screen media.
  4. Wait for fonts and any application data that must appear.
  5. Call page.pdf() with an explicit output contract.
  6. Inspect the generated file in a real PDF viewer and test it with representative content.

Runnable Node.js example

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  try {
    const page = await browser.newPage();
    await page.setViewport({ width: 1440, height: 900, deviceScaleFactor: 1 });

    await page.goto('https://example.com/report', {
      waitUntil: 'networkidle2',
      timeout: 30_000
    });

    // Replace this with a condition your application controls.
    await page.waitForSelector('[data-report-ready="true"]', {
      timeout: 30_000
    });

    await page.pdf({
      path: 'report.pdf',
      format: 'A4',
      printBackground: true,
      preferCSSPageSize: true,
      margin: {
        top: '16mm',
        right: '14mm',
        bottom: '16mm',
        left: '14mm'
      },
      displayHeaderFooter: false,
      timeout: 30_000
    });
  } finally {
    await browser.close();
  }
})();

networkidle2 is a useful starting point, not proof of readiness. Analytics, long polling, lazy components and client-side requests can keep changing the page after navigation appears complete. A server-rendered page may need only a selector; a dashboard may need a flag set after data and charts finish rendering.

Wait for the right ready state

Navigation readiness

waitUntil: 'networkidle2' waits for a quiet network period, but it cannot know whether your application has finished rendering. Use a navigation timeout that reflects the slowest acceptable request, and handle timeout failures rather than silently printing a partial page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Brother DCP-L2640DW Wireless Compact Monochrome Multi-Function Printer, Copy, Scan, Duplex, Mobile Printing
  • BEST FOR SMALL BUSINESSES – Engineered for extraordinary productivity, the Brother DCP-L2640DW Monochrome (Black & White) 3-in-1 combines laser printer, scanner, copier in one compact footprint and delivers high-quality black & white prints
  • FAST PRINTER WITH EFFICIENT SCANNING – Produces documents quickly with print speeds up to 36 ppm(2) and scan speeds up to 23.6/7.9 ipm(3) (black/color). A 50-page auto document feeder(4) allows for convenient, time saving multi-page scanning and copying
  • FLEXIBLE CONNECTION OPTIONS – Easily navigate the changing demands of your business with secure multi-device connectivity via built-in dual-band wireless (2.4GHz / 5GHz) and Ethernet. Or connect locally to a single computer via USB interface
  • BROTHER MOBILE CONNECT APP – Print, scan, and manage your wireless printer anytime, from almost anywhere from your mobile device. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(5)
  • CHOOSE BROTHER GENUINE TONER – When it’s time to replace your toner, be sure to choose Brother Genuine TN830 or TN830XL replacement toner. And with Refresh EZ Print Subscription Service, you’ll never worry about running out of toner again and you’ll enjoy savings of up to 50%(6) on Brother Genuine Toner. Get started with Refresh today with a Free Trial(1)

Application readiness

Add an explicit marker such as data-report-ready="true" after the final API response, chart render and image setup. Other useful conditions include a known heading, a row count, a loading element disappearing, or a page-level promise exposed for automation. For a fixed animation or delayed widget, page.waitForTimeout() can help, but a semantic condition is less brittle.

Lazy-loaded images

Scroll through long documents or trigger the application’s image loader before printing. Otherwise, below-the-fold images may be absent or represented by placeholders. Waiting for all relevant image elements to report complete and a non-zero natural width is safer than relying on a fixed delay.

Print media versus screen media

page.pdf() uses the print CSS media type by default. That is usually correct for a document intended for paper or conventional PDF reading: print styles can hide navigation, change colors and reflow columns. If the PDF must match the on-screen design, call:

await page.emulateMediaType('screen');
await page.pdf({ path: 'screen-style.pdf', printBackground: true });

Choose one deliberately. Test both when a product specification says “match the website,” because screen and print styles can differ in visibility, spacing and page breaks. A print stylesheet should define what is hidden, how links and tables behave, and where headings may break.

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

Define the paper and page-break contract

Format, width and height

Use format for a named paper size such as A4 or Letter. If you provide format, it takes priority over width and height. The documented default is Letter, so do not rely on that default for an international workflow. Use custom width and height when the output is a receipt, label or other non-standard page.

Rank #2
Brother HL-L2405W Wireless Compact Monochrome Laser Printer with Mobile Printing, Black & White Output | Includes Refresh Subscription Trial(1), Works with Alexa
  • BEST FOR HOMES & HOME OFFICES – Engineered for consistent, premium print quality, the Brother HL-L2405W Monochrome (Black & White) Laser Printer delivers sharp, crisp prints at an affordable price. Prints one-sided documents at speeds up to 30ppm(2)
  • COMPACT, CONNECTED PRINTER – Flexible connection options make this an ideal printer for home use and at-home offices. Securely connect to multiple devices with built-in dual-band wireless (2.4GHz/5GHz) or locally to a single computer via USB interface
  • BROTHER MOBILE CONNECT APP – Manage your printer remotely and print from your mobile device anytime, from almost anywhere. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(3)
  • VERSATILE PAPER HANDLING – Enjoy seamless, reliable everyday printing with the 250-sheet paper tray(4) and a manual feed slot that enables printing on envelopes and specialty pape
  • BROTHER IS AT YOUR SIDE – Backed by Brother with a 1-year limited warranty and free online, call, or live chat support for the life of your printer

CSS @page sizing

Set preferCSSPageSize: true when the document’s stylesheet owns the paper definition:

@page {
  size: A4 portrait;
  margin: 16mm 14mm;
}

@media print {
  .screen-only { display: none !important; }
  h1, h2, h3 { break-after: avoid; }
  table, figure { break-inside: avoid; }
}

With that option enabled, CSS @page sizing takes priority over the API paper settings. Keep the ownership model clear: either configure dimensions in code or let the print stylesheet control them, and test the deployed version when both are present.

Margins and orientation

PDF margins default to none. Set all four margins explicitly, especially when headers, footers or edge-sensitive content are involved. Set landscape: true for wide tables, or use portrait deliberately for normal reports. Do not fix overflow by shrinking everything first; revise the layout, split wide tables, or choose landscape.

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

Scale and page ranges

The documented scale range is 0.1 through 2, with 1 as the normal starting point. Lower values fit more content but reduce legibility; higher values can create unexpected extra pages. Use pageRanges when you need selected pages, and verify the resulting page count because ranges are applied to the rendered document.

Colors, backgrounds and fonts

Background graphics and print colors

printBackground defaults to false. Enable it for branded panels, chart fills and colored table cells:

Rank #3
Sale
Canon imageCLASS LBP6030w - Monochrome Single-Function Wireless Compact Wireless Laser Printer, 1 Year Limited Warranty, 19 PPM, White - Print Only
  • FAST PRINT SPEEDS: Print up to 19 pages per minute.
  • COMPACT DESIGN: Space-saving, compact design fits anywhere in your home, school or small office.
  • WIRELESS CONNECTIVITY: Print from almost anywhere in your workspace using your compatible mobile device.
  • PAPER CAPACITY: Up to 150 sheets.
  • SUSTAINABILITY: Uses less than 2 watts in Energy Saver mode.
await page.pdf({
  path: 'branded.pdf',
  format: 'A4',
  printBackground: true
});

Browsers also adjust colors for printing by default. If exact CSS colors are part of the output contract, add -webkit-print-color-adjust: exact (and test the result in your target browser). Exact color output can increase ink usage, so use it only where fidelity matters.

Font readiness

Puppeteer waits for fonts by default, but a page running in the background may need to be brought to the front for that wait to resolve:

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.
await page.bringToFront();
await page.evaluate(() => document.fonts.ready);
await page.pdf({ path: 'fonts-ready.pdf' });

Ensure font files are reachable from the capture environment, serve the correct CORS headers, and include fallbacks. A missing webfont can change line wrapping and therefore every page break.

Headers, footers and accessibility-related options

Use displayHeaderFooter: true with HTML templates when every page needs a title, date or page number. Header and footer templates run in a restricted context; inline styles and the built-in classes such as pageNumber and totalPages are safer than relying on the main document’s CSS.

The current options reference documents experimental outline and tagged output. Treat those controls as version-sensitive: validate the generated structure with the exact Puppeteer and browser versions deployed, and do not promise accessibility behavior without inspecting the resulting PDF.

Rank #4
Brother HL-L2460DW Wireless Compact Monochrome Laser Printer with Duplex, Mobile Printing, Black & White Output | Includes Refresh Subscription Trial(1), Works with Alexa
  • BEST FOR HOME OFFICES & SMALL TEAMS – Engineered for consistent, premium print quality, the Brother HL-L2460DW Monochrome (Black & White) Laser Printer produces documents that are clear, crisp, and easy to review and share, all at an affordable price
  • COMPACT, CONNECTED, EXCEPTIONALLY EFFICIENT– Connect with built-in dual-band wireless (2.4GHz/5GHz), Ethernet, or to a single computer via USB interface. Prints at speeds up to 36ppm(2), plus automatic duplex printing saves time and reduces paper waste
  • BROTHER MOBILE CONNECT APP – Manage your wireless printer remotely and print from your mobile device anytime, from almost anywhere. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(3)
  • VERSATILE PAPER HANDLING – Tackle high-volume black & white printing with the 250-sheet capacity paper tray.(4) The manual feed slot enables printing on envelopes and specialty paper
  • BROTHER IS AT YOUR SIDE – Backed by Brother with a 1-year limited warranty and free online, call, or live chat support for the life of your printer

Browser version and deployment discipline

Puppeteer’s compatibility guarantee applies to its bundled browser. Pointing executablePath at an independently installed Chrome or Chromium build is possible, but it is your responsibility to validate that combination. Differences in fonts, print rendering, sandbox configuration and PDF behavior can surface only in production.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Pin Puppeteer and deploy the browser it expects.
  • Render a smoke-test document during deployment.
  • Run visual or structural checks for page count, required text, images and fonts.
  • Keep the same OS font packages and locale in CI and production.
  • Use a container or machine profile that has enough memory for your largest pages.

Common failures and precise fixes

Symptom Likely cause Fix
PDF contains a loading spinner Navigation ended before client rendering Wait for an application-specific selector or readiness flag.
Charts or images are missing Lazy loading, blocked requests or an early print Trigger lazy content, wait for image completion, and inspect failed network requests.
Colors look washed out Print color adjustment or disabled backgrounds Set printBackground: true and use -webkit-print-color-adjust: exact where required.
Webfont is replaced Font request failed or readiness wait stalled Check font URLs and CORS, call page.bringToFront(), then await document.fonts.ready.
Pages have unexpected size Implicit Letter default or competing CSS/API settings Set format or dimensions explicitly and decide whether preferCSSPageSize is authoritative.
Content is clipped at the edge No margins, oversized elements or incorrect orientation Set margins, use landscape for wide content, and fix CSS overflow.
page.pdf() times out Fonts, network idle or a page script never settles Increase the option timeout only after fixing readiness; replace indefinite waits with a bounded application condition.
Works locally, fails in production Different browser, fonts, sandbox or OS Align the bundled browser and runtime, then reproduce with production assets.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability and cost choices

PDF generation is a browser-rendering workload. Reuse a browser process when safe, create isolated pages per job, and always close pages in a finally block. Limit concurrency according to available memory; many large pages rendered simultaneously can cause crashes before CPU becomes the bottleneck.

Cache stable assets and avoid waiting for analytics or advertisements that do not belong in the document. Set bounded navigation and PDF timeouts, record the URL, Puppeteer version, browser revision and elapsed times, and retain a failure screenshot or HTML snapshot for diagnosis. Retries help transient network failures, but repeating a deterministic selector timeout only adds load. For user-supplied URLs, enforce an allowlist or outbound-network policy to reduce server-side request forgery risk.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server when you need an image or PDF without maintaining Puppeteer. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. An MCP server lets Claude, Cursor and other MCP clients call take_screenshot, get_page_info and capture_pdf.

For a PDF, use the API endpoint and set the output options required by your document:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -d output=pdf -o report.pdf

See the ScreenshotNeo documentation for the complete parameter list, including paper size, margins, landscape mode, page ranges, custom CSS and JavaScript, waiting rules, cookies, headers and signed asynchronous jobs.

Best Value
HP LaserJet M110w Wireless Black & White Printer, Print, Fast speeds, Easy Setup, Mobile Printing, Best-for-Small Teams
  • FROM AMERICA'S MOST TRUSTED PRINTER BRAND – Perfect for small teams printing professional-quality black & white documents and reports. Perfect for 1-3 people
  • WORLD'S SMALLEST LASER IN ITS CLASS – Precision laser printing that fits anywhere
  • FAST PRINT SPEEDS – Up to 21 black-and-white pages per minute single-sided
  • WIRELESS WITH SELF-RESET – Helps you stay connected
  • PRINT FROM ANY DEVICE – Wireless printing from any mobile device, PC or tablet. Works with Microsoft, Mac, AirPrint, Android, Chromebook and more

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com", "output": "pdf"},
    timeout=90,
)
r.raise_for_status()
open("report.pdf", "wb").write(r.content)

Node.js

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com',
  output: 'pdf'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
require('fs').writeFileSync('report.pdf', Buffer.from(await res.arrayBuffer()));

Every feature is included on every plan: full-page capture, element selection, device and retina settings, custom headers and cookies, request blocking, geolocation, transparent backgrounds, resizing, caching with your chosen TTL, signed links, async webhooks, bulk capture of up to 100 URLs per call, a usage API and an OpenAPI specification. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Frequently Asked Questions

Does Puppeteer create a PDF from the DOM or from a screenshot?

It prints the rendered page through Chromium’s PDF engine, applying print CSS and pagination rather than producing a single raster image.

Should I use Letter or A4?

Use the paper size required by your readers and downstream workflow, and set it explicitly instead of relying on Puppeteer’s Letter default.

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

Can I use an installed Chrome binary?

Yes, but Puppeteer’s compatibility guarantee covers its bundled browser; an independently installed build requires your own validation.

Why does a PDF have more pages after a font change?

Different font metrics alter line wrapping and element heights, which changes pagination. Make font availability and readiness part of your deployment tests.

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.

Read next

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.