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

Run the page’s JavaScript, wait for a condition that proves the printable content is ready, and only then call Puppeteer’s page.pdf(). A practical baseline is page.goto() with waitUntil: 'networkidle2', followed by an application-specific check such as page.waitForFunction() or an awaited function exposed by the page. This avoids PDFs that capture a loading shell, stale data, or an unfinished chart.

The reliable sequence

Headless Chromium executes JavaScript during navigation. Your code must distinguish “the document loaded” from “the report is ready to print.” Use this sequence:

  1. Launch Chromium and create a page.
  2. Navigate with a suitable lifecycle condition.
  3. Await the page operation or readiness predicate that represents completed data and layout work.
  4. Select print or screen media and configure PDF options.
  5. Call await page.pdf().
  6. Close the browser in a finally block.

Puppeteer’s PDF API renders with print CSS media by default. The navigation and readiness waits are separate concerns: network idle describes requests, while your application state describes whether the report is actually usable.

Prerequisites and a complete JavaScript example

Install Puppeteer

npm install puppeteer

The API names and defaults below correspond to current Puppeteer documentation around versions 25.10.0–25.12.0. Check the documentation for the version installed in your project before relying on a changed default.

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.
#1 Best Overall
Epson EcoTank ET-2800 Wireless Color All-in-One Supertank Printer - Black
  • INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
  • COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
  • ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
  • HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs

Wait for a page-defined readiness flag

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
try {
  const page = await browser.newPage();
  await page.goto('https://example.com/report', {
    waitUntil: 'networkidle2',
  });

  // The site must set this only after data and print layout are ready.
  await page.waitForFunction(
    () => window.reportReady === true,
    { timeout: 30_000, polling: 'mutation' }
  );

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

window.reportReady is illustrative, not a Chromium or Puppeteer signal. The application must set it after its own fetches, chart rendering, fonts, and print-only layout work have completed. If the page cannot expose a flag, wait for a selector that appears only in the completed state or use an awaited page function.

Ways to wait for JavaScript work

Await a known asynchronous operation with page.evaluate()

When the page supplies a callable function that returns a Promise, run it in the page context and await the result:

await page.evaluate(async () => {
  await window.prepareReportForPrint();
});

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

This assumes the site defines prepareReportForPrint. It is not a built-in Puppeteer method. The Promise must resolve only after the operation needed for printing is complete.

Wait for an application predicate with page.waitForFunction()

Use this when readiness is represented by a value in the page:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.waitForFunction(
  () => document.querySelector('[data-print-ready="true"]') !== null,
  { timeout: 30_000, polling: 100 }
);

The predicate is evaluated in the page context until it becomes truthy or the timeout expires. Keep the predicate tied to a real completion signal, such as a data-loaded attribute, a completed render state, or a page-owned flag.

Use navigation and network-idle waits as milestones

await page.goto(url, { waitUntil: 'networkidle2' });

The official PDF example uses networkidle2 before generating the file. It is useful when the page settles after navigation, but it does not prove that application work is complete. Analytics, polling, WebSockets, long-lived requests, or delayed rendering can make network activity a poor proxy for print readiness.

Rank #2
Sale
Epson EcoTank Photo ET-8550 Wireless Wide-Format All-in-One Tank Printer
  • CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
  • INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
  • PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
  • ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴

Puppeteer also provides page.waitForNetworkIdle(). It waits for network activity to remain idle for the configured idle period and always waits at least that idle time. Pair it with a page-specific condition when the report has a meaningful completion state.

Why an arbitrary sleep is a weak default

await new Promise(resolve => setTimeout(resolve, 5000));

A fixed delay may be too short on a slow run and unnecessarily long on a fast one. Prefer a known Promise, readiness predicate, selector, or network-idle condition. A delay can still be a deliberate supplement when an animation or debounce has no observable completion signal; document why it is needed and keep it bounded.

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

Make the PDF match the intended design

Print media versus screen media

page.pdf() uses the print CSS media type by default. If the page’s screen stylesheet is the desired output, switch media first:

await page.emulateMediaType('screen');
await page.pdf({ path: 'screen-styled.pdf' });

Otherwise, leave the default in place and maintain print-specific rules with @media print and @page.

Important PDF options

Option Purpose and default When to use it
printBackground Prints background graphics; default is false. Set true for colored panels, chart fills, and background images.
waitForFonts Waits for fonts; documented default is true. Keep enabled when typography affects line breaks or pagination.
preferCSSPageSize Lets CSS @page size take priority over explicit dimensions. Use when the document owns paper size through CSS.
format, width, height Define paper dimensions. Use a named format such as A4, or explicit dimensions for a custom sheet.
landscape Changes orientation. Use for wide tables and dashboards.
margin Sets page margins. Reserve space for readable headers, footers, or binding.
scale Scales rendered content. Adjust fit carefully; excessive scaling can make text unreadable.
pageRanges Selects pages to output. Export only relevant pages from a long report.

Chromium modifies PDF colors for print by default. If exact colors matter, use the documented CSS property -webkit-print-color-adjust in the page’s print styles.

A production-oriented pattern

import puppeteer from 'puppeteer';

export async function renderReport(url, outputPath) {
  const browser = await puppeteer.launch();
  try {
    const page = await browser.newPage();
    page.setDefaultTimeout(30_000);

    await page.goto(url, { waitUntil: 'networkidle2' });

    await page.waitForFunction(
      () => window.reportReady === true,
      { timeout: 30_000 }
    );

    // Keep print CSS. Use 'screen' here only if screen styling is required.
    await page.pdf({
      path: outputPath,
      format: 'A4',
      printBackground: true,
      preferCSSPageSize: true,
      waitForFonts: true,
    });
  } finally {
    await browser.close();
  }
}

await renderReport('https://example.com/report', 'report.pdf');

Set the readiness flag only after asynchronous data has arrived, components have rendered, and any print preparation has run. If you control the page, expose a small, deterministic contract rather than making the PDF worker guess from timing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
HP Smart Tank 5000 Wireless All-in-One Ink Tank Printer, Scanner, Copier with 2 Years of Ink Included, Best-for-Home, Cartridge-Free, Refillable and AI-Enabled. (5D1B6A)
  • SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
  • INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
  • KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
  • PREMIUM SUPPORT - Strong technical expertise to solve issues faster
  • THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.

Troubleshooting

The PDF contains a spinner or empty chart

Cause: navigation completed before application rendering. Fix: add a real readiness flag, selector, or awaited function. Keep networkidle2 as a milestone, not the sole assertion.

waitForFunction times out

Cause: the predicate is never true, the flag is set in a different frame, or the page failed earlier. Fix: verify the flag in the page, increase the timeout only when the workload genuinely needs it, and capture console and page-error events while diagnosing:

page.on('console', message => console.log('[browser]', message.text()));
page.on('pageerror', error => console.error('[page error]', error));

Network idle never arrives

Cause: polling, analytics, streaming, or another long-lived request keeps activity alive. Fix: navigate with a less restrictive lifecycle milestone and rely on an application-specific readiness predicate, or use page.waitForNetworkIdle() with an appropriate bounded setting.

Colors or backgrounds are missing

Cause: printBackground defaults to false, and print CSS may intentionally alter colors. Fix: set printBackground: true and adjust print styles, including -webkit-print-color-adjust when exact colors are required.

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.

The PDF uses the wrong layout

Cause: print media is active by default. Fix: inspect @media print rules, or call page.emulateMediaType('screen') before page.pdf() when screen CSS is the requirement.

Fonts change pagination

Cause: the intended webfont was not available when layout was captured. Fix: keep waitForFonts: true, ensure the font request succeeds, and make the readiness signal occur after font-dependent rendering.

Rank #4
NDYIN Portable Printers Wireless for Travel, N80 Bluetooth Thermal Printer
  • Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
  • No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
  • Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
  • Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
  • The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art

The browser remains running after an error

Cause: cleanup is not guaranteed on exceptions. Fix: put PDF generation inside try and close the browser in finally, as in the examples.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and operational choices

  • Use the narrowest meaningful wait. A page-owned completion signal avoids both premature output and needless delay.
  • Bound every wait. Timeouts turn a stuck page into a diagnosable failure instead of an indefinitely running job.
  • Keep rendering deterministic. Disable or account for animations, make data snapshots consistent, and ensure resources needed for the report are reachable from the Chromium process.
  • Choose output settings deliberately. Background graphics, paper size, margins, scale, orientation, page ranges, and CSS page-size preference all affect pagination and file appearance.
  • Measure the stages you own. Record navigation, readiness, and PDF-generation durations separately; a slow readiness check and a slow PDF encode have different remedies.
  • Pin and review Puppeteer versions. API behavior and defaults can change, so align implementation and documentation with the installed version.

Or skip the browser setup

For a hosted capture that returns a PDF, ScreenshotNeo accepts one GET request. Its cleaning step accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and whether it was billed. It also provides an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. See the ScreenshotNeo documentation for parameters.

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

cURL

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

Python

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

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo supports PDF paper size, margins, landscape mode, page ranges, custom JavaScript and CSS, waits for selectors, delays or network idle, custom headers and cookies, geolocation and timezone, signed links, asynchronous jobs, bulk capture of up to 100 URLs per call, caching with a chosen TTL, usage reporting, and an OpenAPI specification. Its parameter names are compatible with those used by other screenshot APIs, which can simplify migration.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account to start with those 1,000 monthly shots.

Frequently Asked Questions

Does Chromium wait for every JavaScript timer automatically?

No. It executes JavaScript, but your script must await the operation or condition that defines readiness before calling page.pdf().

Can I print only selected PDF pages?

Yes. Puppeteer’s page.pdf() supports pageRanges for selecting output pages.

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

Is networkidle2 a guarantee that a report is complete?

No. It is a network-activity milestone. Pair it with an application-specific readiness check when rendering has additional work.

Quick Recap

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.