The shortest reliable workflow is: launch Puppeteer, create a page with await browser.newPage(), load a URL or inject HTML, then call await page.pdf({ path: 'output.pdf' }). Puppeteer renders with print CSS by default, waits for fonts, and lets you control paper size, margins, backgrounds, orientation, page ranges, and more. The complete examples below show both file-based and in-memory output, plus the settings that most often change the result.
Minimal example: navigate a new page and save a PDF
Install Puppeteer in your project, then use an async function (or an environment that supports top-level await):
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();
}
browser.newPage() creates a Page in the browser’s default context. page.goto() loads the target document, and page.pdf() writes the rendered PDF when a path is supplied. The finally block closes Chromium even if navigation or PDF generation fails.
Generate a PDF from HTML created in the script
When the document does not live at a URL, replace goto() with setContent(). Wait for the resources your page needs before creating the PDF.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware match#1 Best Overall
- 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
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.setContent(`
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
@page { size: A4; margin: 18mm; }
body { font-family: Arial, sans-serif; }
h1 { color: #174ea6; }
</style>
</head>
<body>
<h1>Invoice 1007</h1>
<p>Generated from HTML in Puppeteer.</p>
</body>
</html>
`, { waitUntil: 'networkidle0' });
await page.pdf({ path: 'invoice.pdf', format: 'A4', printBackground: true });
} finally {
await browser.close();
}
For remote images, web fonts, or JavaScript-generated content, ensure those assets have finished loading. A network-idle condition is useful, but an application-specific selector or explicit wait can be more precise when a page keeps long-lived connections open.
What page.pdf() returns and where output goes
- Write a file: pass
path: 'output.pdf'. The path is resolved by your Node.js process, so use an absolute path when a worker’s current directory is uncertain. - Receive bytes: omit
path. The method returns aPromise<Uint8Array>, which you can send in an HTTP response, upload, or write with Node’s filesystem APIs. - Stream: use
page.createPDFStream(options)when the consumer needs incremental data. It returns aReadableStream<Uint8Array>.
const pdfBytes = await page.pdf({ format: 'Letter', printBackground: true });
// Example: return pdfBytes from an API handler with Content-Type application/pdf.
Control paper size, CSS sizing, and orientation
| Setting | Use it when | Important behavior |
|---|---|---|
format |
You want a named paper size such as Letter or A4. |
Letter is the documented default. If set, it takes priority over width and height. |
width and height |
You need an exact custom paper dimension. | Use CSS units such as mm, in, or px; do not rely on these when format is also set. |
preferCSSPageSize |
Your stylesheet’s @page rule defines the authoritative size. |
It defaults to false. Set it to true to give CSS page size priority instead of scaling the content into the selected paper. |
landscape |
Tables, dashboards, or wide screenshots need horizontal pages. | Defaults to false (portrait). |
await page.pdf({
path: 'wide-report.pdf',
format: 'A4',
landscape: true,
margin: { top: '12mm', right: '10mm', bottom: '12mm', left: '10mm' }
});
Make screen styling, colors, and backgrounds appear correctly
Print media versus screen media
PDF generation uses print CSS media by default. If the page looks different from what users see in a browser, switch media before calling pdf():
await page.emulateMediaType('screen');
await page.pdf({ path: 'screen-style.pdf', printBackground: true });
Use print media when you maintain a dedicated print stylesheet; use screen media when the on-screen layout is the intended document.
Background graphics and exact colors
printBackground defaults to false. Set it to true for colored sections, background images, and dashboard panels. Browsers may modify colors for printing. Add this CSS when color fidelity matters:
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →html {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
Color output can still vary with Chromium, CSS, and embedded assets, so inspect a representative PDF in the viewer used by your recipients.
Rank #2
- 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⁴
Wait for content that is not ready at navigation time
- Fonts: Puppeteer’s PDF method waits for fonts by default; the options reference calls this
waitForFonts, whose default istrue. - Lazy images: scroll or trigger the application to load them before generating the PDF.
- Async application data: wait for a stable selector rather than guessing a delay.
- Animations: disable them in print CSS or wait until the final state to avoid capturing an intermediate frame.
await page.goto(url, { waitUntil: 'domcontentloaded' });
await page.waitForSelector('#report-ready');
await page.evaluate(() => document.fonts.ready);
await page.pdf({ path: 'report.pdf', printBackground: true });
If a page never reaches network idle because of analytics or a WebSocket, do not wait forever for that event. Use a readiness element and a bounded timeout appropriate to your application.
Select pages, add finishing details, and tune scale
Page ranges
Restrict output with a comma-separated range such as 1-5, 8, 11-13:
await page.pdf({ path: 'extract.pdf', pageRanges: '1-5, 8, 11-13' });
Headers, footers, and scale
Margins, header and footer templates, and scale can finish a report. Header/footer templates use Chromium’s print-template markup (for example, page-number and date classes). Keep enough top and bottom margin for those templates; otherwise content can overlap them.
await page.pdf({
path: 'numbered.pdf',
format: 'Letter',
displayHeaderFooter: true,
headerTemplate: '<span style="font-size:8px;margin-left:20px">Quarterly report</span>',
footerTemplate: '<span style="font-size:8px;margin:auto">Page <span class="pageNumber"></span> of <span class="totalPages"></span></span>',
margin: { top: '20mm', bottom: '20mm' },
scale: 0.95
});
Experimental accessibility options
The current options reference marks tagged and outline as experimental. It lists tagged: true and outline: false as defaults. Treat these as version-sensitive capabilities, not a guarantee of identical accessibility or outline quality in every PDF viewer.
Version and protocol considerations
The official guide and API references used for this workflow describe Puppeteer 25.12.0, while the Browser.newPage() reference shows 25.10.0. Those labels describe the documentation state, not necessarily the version installed in your project; check your lockfile and installed package before relying on a newly added option.
Rank #3
- 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.
If you automate through WebDriver BiDi, Puppeteer documents a narrower PDF option set: format, height, landscape, margin, pageRanges, printBackground, scale, and width. Verify protocol support before using CSS page-size preference, templates, or other options over BiDi.
Troubleshooting common PDF failures
“Cannot find module ‘puppeteer’”
Install the dependency in the same project and runtime that executes the script, then run it from that project’s directory. If you use a browserless package, ensure a compatible Chrome/Chromium executable is configured.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →The PDF is blank or missing application data
Navigation completion does not prove that client-side rendering is complete. Wait for a page-specific ready selector, check console and network errors, and generate the PDF only after the data appears in the DOM.
Images or fonts are missing
Confirm the process can reach each asset URL, avoid expiring authenticated links, wait for document.fonts.ready, and ensure lazy images have been loaded. For private assets, set the page’s authentication state before navigation.
Colors or backgrounds disappear
Set printBackground: true. If print CSS is hiding the component, use emulateMediaType('screen') or revise the print stylesheet. Add the print-color-adjust declarations when exact colors are required.
Rank #4
- 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
Content is clipped or unexpectedly scaled
Check for a conflicting format and @page rule, then choose one sizing authority. Use preferCSSPageSize: true for CSS-defined paper, adjust margins, and reserve space for headers and footers. Reduce scale only after fixing the paper and margin model.
Recommended Free Tools
The script hangs
Long-lived requests can prevent networkidle0. Prefer domcontentloaded plus a readiness selector, set explicit navigation and selector timeouts, and always close the browser in finally.
Or skip the browser setup
If you need a screenshot or PDF endpoint rather than managing Chromium yourself, ScreenshotNeo accepts one request for a URL. Its clean-shot steps accept consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. It also offers an MCP server for AI clients such as Claude and Cursor, with take_screenshot, get_page_info, and capture_pdf.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for PDF parameters and the other 63 capture options, including paper size, margins, landscape mode, page ranges, custom CSS and JavaScript, cookies, headers, waiting rules, blocking, caching, signed links, asynchronous jobs, and bulk capture.
The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan. Create a free ScreenshotNeo account to try it.
Practical checklist before shipping a PDF
- Use
newPage()and close the browser in all code paths. - Choose
goto()for a URL orsetContent()for generated HTML. - Wait for a real ready condition, fonts, images, and data.
- Decide between print and screen media.
- Set paper size, margins, orientation, backgrounds, and page ranges explicitly.
- Test long tables, page breaks, private assets, and representative fonts.
- Check the installed Puppeteer version and, for BiDi, the supported option subset.
Frequently Asked Questions
Does Puppeteer create a PDF from a blank new page?
Yes. Call await browser.newPage(), then use setContent() to place HTML in that page before calling page.pdf().
Can I return the PDF without writing a file?
Yes. Omit path and use the returned Uint8Array, or use page.createPDFStream() for a readable stream.
Why does my PDF differ from the browser tab?
PDFs use print media by default. Call page.emulateMediaType('screen') when the screen stylesheet is the intended appearance.
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.

