Guide
Generating PDFs with Puppeteer's page.pdf() Method
Learn how to use Puppeteer's page.pdf() to create a PDF from a URL, set options, verify the output, and recover from common failures.
Published by Tasadduq Burney
25 Mar 2026, 14:48 UTC
2 min96.4K views0

Desired outcome
Create a PDF file of a web page using Puppeteer’s page.pdf() method, save it to a chosen local path, and verify that the file is usable.
Prerequisites
- Node.js version 14 or newer installed.
- The
puppeteernpm package added to your project (npm i puppeteer). - A target URL that can be reached from the runtime environment (no authentication or firewall blocking).
Procedure
- Launch Puppeteer in headless mode.
- Open a new tab/page.
- Navigate to the URL, waiting until the network is idle.
- If the page layout depends on a specific viewport, set it with
page.setViewport. - Define PDF options such as output path, paper format, margins, and whether to print background graphics.
- Call
await page.pdf(pdfOptions)to generate the PDF. - Close the browser instance.
const puppeteer = require('puppeteer');
async function generatePdf(url, outputPath) {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
// Optional: set viewport if needed
await page.setViewport({ width: 1280, height: 800 });
await page.goto(url, { waitUntil: 'networkidle2', timeout: 30000 });
const pdfOptions = {
path: outputPath,
format: 'A4',
printBackground: true,
margin: { top: '20mm', right: '15mm', bottom: '20mm', left: '15mm' }
};
await page.pdf(pdfOptions);
await browser.close();
}
// Example usage
// generatePdf('https://example.com', './example.pdf').catch(console.error);
Expected checks
- Verify that
outputPathexists on the file system. - Check that the file size is greater than zero bytes.
- Open the PDF in a viewer (e.g., Adobe Reader, Okular) to confirm content renders.
- Optionally inspect the PDF with
pdftkorqpdfto check page count and ensure background colors are present (indicatingprintBackgroundwas applied).
Recovery options
If the PDF is missing or zero‑size:
- Delete any partially written file to avoid confusion.
- Increase the navigation timeout (e.g.,
timeout: 60000) in thepage.gotocall. - Confirm the URL is reachable from the host using
curlor a similar tool. - Re‑run the script.
Note: Headless Chrome may render some CSS or JavaScript differently than headed mode. If layout issues appear, explicitly set the viewport or add a short await page.waitForTimeout after navigation to allow dynamic content to settle.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.