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

To save a webpage as a PDF without opening a browser print dialog, use Puppeteer’s page.pdf() method and provide a file path: await page.pdf({ path: 'output.pdf' }). Puppeteer renders the page with print CSS, waits for fonts by default, and writes the resulting PDF directly to disk. This unattended workflow is different from window.print(), which asks a user to choose print settings and a destination.

Use page.pdf(), not the native print dialog

The phrase “save a PDF from a print dialog” can describe two different jobs:

  • Interactive printing: window.print() prompts a person to print the page. The person operates the browser’s print-preview interface and chooses “Save to PDF” or another destination.
  • Automated PDF generation: Puppeteer creates the PDF file itself with Page.pdf(). You select the output path in code, so no native print-preview window is required.

Puppeteer’s documented PDF workflow supports the second job. The official API does not provide a supported recipe for clicking the native print dialog’s Save controls in an unattended process. For servers, CI jobs, scheduled reports and batch exports, direct PDF generation is the reliable boundary: prepare the page, call page.pdf(), then close the browser.

Minimal runnable Node.js example

Install Puppeteer in a new project, then create a script such as save-pdf.mjs:

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
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
  1. mkdir puppeteer-pdf && cd puppeteer-pdf
  2. npm init -y
  3. npm install puppeteer
  4. Save the following code as save-pdf.mjs.
  5. Run node save-pdf.mjs. The file is written relative to the process’s current working directory.
import puppeteer from 'puppeteer';

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

networkidle2 waits for a period with no more than two active network connections. It is useful for ordinary pages, but it does not prove that an application’s client-side data or delayed widgets are ready. Add an application-specific readiness check when your page has one.

Control the output path and handle PDF bytes

Write directly to disk

Set PDFOptions.path to a file name or an absolute path. A relative path is resolved from the current working directory, not necessarily from the directory containing your script.

await page.pdf({ path: '/var/reports/invoice-1042.pdf' });

Ensure the destination directory exists and that the account running Node can write to it. Puppeteer returns after the PDF has been generated.

Keep the PDF in memory

If you omit path, Puppeteer does not write a file. page.pdf() returns the PDF data as a Uint8Array, which you can send in an HTTP response, upload to storage, or process in another service.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const pdfBytes = await page.pdf({ format: 'A4' });
// Example: convert only when an API requires a Node Buffer
const pdfBuffer = Buffer.from(pdfBytes);

Prepare the page before calling page.pdf()

Wait for navigation and application data

Use page.goto() with an appropriate waitUntil value. For a single-page application, wait for a selector that appears only after the report is populated:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
await page.goto('https://example.com/report/1042', { waitUntil: 'domcontentloaded' });
await page.waitForSelector('[data-report-ready]', { timeout: 30000 });

You can also use page.waitForNetworkIdle(). Treat network idleness as one signal, not as a universal readiness guarantee: analytics, long polling and delayed rendering can make it misleading.

Choose screen or print styling

page.pdf() uses print media by default. That means rules inside @media print apply, and a layout designed only for the screen may change.

// Use screen-media rules when the PDF should match the screen layout
await page.emulateMediaType('screen');
await page.pdf({ path: 'screen-style.pdf' });

Use this only when screen styling is the intended output. Otherwise leave the default print media and fix the page’s print stylesheet.

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.

Wait for fonts and images

Puppeteer waits for fonts by default. If a page loads images lazily, scroll or trigger the application’s own “load more” behavior before generating the PDF. For a background tab whose fonts do not settle, bringing the page to the front can help:

await page.bringToFront();
await page.evaluate(() => document.fonts.ready);
await page.pdf({ path: 'fonts-ready.pdf' });

Do not use a long arbitrary delay as your only readiness strategy. A selector or application event is usually faster and more deterministic.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Important PDFOptions settings

Option What it controls Typical use
format Named paper size; Letter is the default. format: 'A4' for international reports.
width, height Explicit paper dimensions. Custom receipts or labels.
landscape Rotates the page orientation. Wide tables and dashboards.
preferCSSPageSize Lets CSS @page dimensions take precedence over the selected paper size. Documents with carefully defined page geometry.
margin Top, right, bottom and left margins. Prevent headers, footers or content from touching the edge.
scale Scales rendered content. Reduce clipping or fit a dense report.
printBackground Includes background graphics; default is false. Set true for colored panels and background images.
pageRanges Limits output to selected pages. pageRanges: '1-3'.
displayHeaderFooter Enables generated header and footer templates. Page numbers, dates and document titles.
waitForFonts Waits for fonts before printing; defaults to true. Keep the default unless you have a specific reason to change it.

If you specify format, it takes precedence over explicit width and height. Use CSS such as @page { size: A4; } with preferCSSPageSize: true when the document controls its own page size.

A practical report configuration

await page.pdf({
  path: 'report.pdf',
  format: 'A4',
  printBackground: true,
  preferCSSPageSize: true,
  margin: {
    top: '12mm',
    right: '10mm',
    bottom: '12mm',
    left: '10mm'
  },
  displayHeaderFooter: true,
  headerTemplate: '<span></span>',
  footerTemplate: '<span style="font-size:10px;width:100%;text-align:center">Page <span class="pageNumber"></span> of <span class="totalPages"></span></span>'
});

Header and footer templates are HTML fragments. Keep them self-contained; page content’s external styles do not automatically apply to them.

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

Fix common layout problems

The PDF does not look like the visible page

  • Check print CSS first. PDF generation uses print media by default.
  • If the screen layout is required, call page.emulateMediaType('screen') before page.pdf().
  • Check format, width, height, margins and scale.
  • Set printBackground: true when colors or background images are missing.
  • Use CSS -webkit-print-color-adjust: exact when exact color reproduction is required by the page’s print styles.

Content is clipped or unexpectedly split

Reduce margins or scale, choose a larger paper size, or adjust the document’s print CSS. For tables and cards, use print-specific break rules and test at the target paper size. preferCSSPageSize can prevent Puppeteer from scaling a document whose @page rule defines the intended dimensions.

Fonts are wrong or text reflows

Confirm that font requests succeed, wait for document.fonts.ready, and keep the default waitForFonts: true. A page that is closed or printed before web fonts finish will fall back to different metrics.

The file is empty, stale or missing data

Navigation completion is not the same as application completion. Wait for a page-specific selector, a known API result, or an in-page readiness flag. If the page uses authentication, establish the session and cookies before navigation. Capture console errors and failed requests while diagnosing.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
page.on('console', message => console.log('[browser]', message.text()));
page.on('requestfailed', request => {
  console.error('Request failed:', request.url(), request.failure()?.errorText);
});

The script hangs or times out

Some sites keep connections open indefinitely. Prefer waitUntil: 'domcontentloaded' plus a specific readiness check, or configure a bounded timeout for the operation. Do not assume that forcing network idle will work for pages with websockets or long polling.

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

The browser cannot launch in a server or container

Check that Puppeteer’s browser installation completed, the runtime has required system libraries, and the process has permission to execute the browser and write the output directory. Keep browser.close() in a finally block so failed jobs do not leave orphaned browser processes.

When a native print dialog is still appropriate

Use window.print() when a human must inspect the preview, select a local printer, choose a destination interactively, or apply settings that your automation does not control. It is a user-interface operation, not a server-side file export. For unattended saving, direct page.pdf() avoids depending on operating-system windows, focus, desktop access and print-preview labels that vary by browser and platform.

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

Or skip the browser setup

ScreenshotNeo can return a webpage image or PDF through one HTTP request. Its API accepts the URL and supports PDF paper size, margins, landscape mode and page ranges. See the ScreenshotNeo documentation for the current parameters.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Before capture, ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page verdict and billing result in X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

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

Operational and cost considerations

  • Browser cost: Every Puppeteer job starts or reuses a Chromium process and consumes CPU and memory. Reuse a browser for batches, but create a fresh page per document and close pages promptly.
  • Determinism: Pin your Puppeteer version, control timezone and locale where relevant, and wait on application state rather than a fixed sleep.
  • Security: Treat target URLs and page content as untrusted. Restrict outbound access, avoid exposing internal services, and protect credentials and generated files.
  • Output validation: Check that the returned bytes are nonempty and that the file exists before reporting success. For important documents, open the PDF in a validation step and record the URL, options and timestamp.

FAQ

Can Puppeteer click “Save to PDF” in the browser print preview?

The documented Puppeteer PDF API creates the file directly. The official workflow does not establish supported automation for the native print-preview Save controls, so use page.pdf() for unattended output.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

What is the default paper size?

format defaults to Letter when no other paper dimensions are selected. Set format: 'A4', explicit dimensions, or a CSS page size when your document requires something else.

Does page.pdf() return a file path?

No. With path, it writes the file to that location. Without path, it returns PDF bytes as a Uint8Array.

Why are background colors missing?

Background graphics are excluded by default. Add printBackground: true and check the page’s print color rules.

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

Frequently Asked Questions

Can Puppeteer click “Save to PDF” in the browser print preview?

The documented Puppeteer PDF API creates the file directly. The official workflow does not establish supported automation for the native print-preview Save controls, so use page.pdf() for unattended output.

What is the default paper size?

format defaults to Letter when no other paper dimensions are selected. Set format: 'A4', explicit dimensions, or a CSS page size when your document requires something else.

Does page.pdf() return a file path?

No. With path, it writes the file to that location. Without path, it returns PDF bytes as a Uint8Array.

Why are background colors missing?

Background graphics are excluded by default. Add printBackground: true and check the page’s print color rules.

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.