Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon 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 NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

How to Generate a PDF of a Website With Playwright

Use Playwright’s page.pdf() to render a website as a PDF, with control over CSS media, paper size, margins, backgrounds, page ranges, and output handling.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Playwright to open a page in a browser, then call page.pdf(). By default, the PDF uses print CSS, Letter paper, no paper margins, and omits background graphics. Choose the media mode and page geometry deliberately, and wait for your site’s content to be ready before exporting.

Generate a website PDF with Playwright

This JavaScript example uses Chromium, navigates to a URL, and writes the resulting PDF to page.pdf in the current working directory:

As an Amazon Associate I earn from qualifying purchases.

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  try {
    const page = await browser.newPage();
    await page.goto('https://example.com');
    await page.pdf({ path: 'page.pdf', format: 'A4' });
  } finally {
    await browser.close();
  }
})();

Install Playwright and its browser binary in your project before running the script. The documented installation command is npx playwright install; see the Playwright browser installation guide. Playwright versions require corresponding browser binaries, so reinstall them when updating Playwright if needed. The code shows the basic flow; the target website may need an additional readiness check before capture.

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

Playwright’s official Page API documentation states: “page.pdf() generates a pdf of the page with print css media.” For navigation and the Page model, see the Pages guide.

#1 Best Overall
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
  • Scanner type: Document
  • Connectivity technology: USB
  • With Auto Scan Mode, the scanner automatically detects what you're scanning
  • Digitize documents and images

Choose print CSS or screen CSS

page.pdf() uses print media by default. That can change layout or hide elements compared with what a visitor sees on screen. To render using screen styles instead, emulate screen media before exporting:

await page.emulateMedia({ media: 'screen' });
await page.pdf({ path: 'page.pdf', format: 'A4' });

Use print media when the page has print-specific styles or should behave like a conventional printout. Use screen media when the PDF should retain the screen layout. Check the resulting PDF: the site’s CSS determines which elements and styles appear in either mode.

Set paper size, margins, and page ranges

The API defaults to Letter paper with no paper margins. You can use a preset such as A4, define dimensions, or let the page’s own @page CSS take precedence.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Option What it controls Important behavior
format Paper preset, such as A4 or Letter Takes precedence over width and height.
width, height Paper dimensions Accept units including px, in, cm, and mm; bare numbers are treated as pixels.
margin Paper margins No paper margins are used by default.
preferCSSPageSize Whether CSS @page sizing takes priority When true, CSS page size takes priority; otherwise content is scaled to fit the selected paper size.
pageRanges Which pages to include For example, 1-5, 8.
scale Content scale Defaults to 1; accepted range is 0.1–2.

For example, set A4 paper, practical margins, and a limited page range like this:

Rank #2
Sale
Epson Workforce ES-400 II High-Speed Color Duplex Desktop Document Scanner | For Computers including PC and Mac with Auto Document Feeder and Image Adjustment Tools
  • FAST DOCUMENT SCANNING — Document scanner with feeder allows you to speed through stacks with a 50-sheet Auto Document Feeder (ADF); Efficient office scanner to help you scan more productively
  • INTUITIVE, HIGH-SPEED SOFTWARE — Quickly scan with this desktop document scanner; Epson ScanSmart Software lets you easily preview scans, email files, upload to the cloud, and more; Plus, automatic file naming saves even more time
  • SEAMLESS INTEGRATION — Easily incorporate your data into most document management software with the included TWAIN driver; Office document scanner integrates seamlessly with business workflows
  • EASY SHARING — Duplex scanner allows you to scan straight to email or popular cloud storage2 services like Dropbox, Evernote, Google Drive, and OneDrive for simple storage and sharing
  • SIMPLE FILE MANAGEMENT — Scanner allows the creation of searchable PDFs with Optical Character Recognition (OCR) and convert scans to editable Word or Excel files effortlessly; Designed for home and office document scanning
await page.pdf({
  path: 'report.pdf',
  format: 'A4',
  margin: { top: '12mm', right: '12mm', bottom: '12mm', left: '12mm' },
  pageRanges: '1-5, 8'
});

When the site’s CSS defines the intended paper dimensions, use preferCSSPageSize: true rather than assuming an A4 or Letter preset will match it.

Include background colors and graphics

Background graphics are excluded by default. Set printBackground: true to include them:

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

Playwright’s Page API documentation notes that PDF generation modifies colors for print by default and identifies the CSS property -webkit-print-color-adjust as guidance for forcing exact colors. The page’s CSS and browser rendering affect the result, so inspect the PDF when color fidelity matters.

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

Add PDF headers and footers

Set displayHeaderFooter: true to enable header and footer templates, then provide headerTemplate and/or footerTemplate. Template scripts are not evaluated, and the page’s styles are not visible inside the templates. Treat them as separate template content rather than assuming the site’s CSS will style them.

Rank #3
HP Smart Tank 5101 Ink Tank Printer | 2 Years of Ink Included | All-in-One
  • 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
  • INNOVATION YOU CAN TRUST. Cartridge-free printing that keeps you printing longer with fewer interruptions, powered by the trusted HP innovation you rely on today
  • PREMIUM SUPPORT - Strong technical expertise to solve issues faster.

Save to a file or use the returned buffer

With path, Playwright writes the PDF to disk; a relative path is resolved from the current working directory. If you omit path, page.pdf() returns a PDF buffer. That lets your application handle the bytes—for example, pass them to another function or save them using its own file-storage flow.

const pdfBuffer = await page.pdf({ format: 'A4' });
// Use pdfBuffer in your application.

Wait for the page to be ready before printing

Navigation alone does not guarantee that an application has finished rendering the content you want in the PDF. A page may load data after its initial document, or render content only after a user-interface state is reached. Make readiness specific to the target site rather than relying on a fixed delay for every page.

For a known page element that marks readiness, wait for that selector before exporting:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.goto('https://example.com');
await page.locator('#report-ready').waitFor();
await page.pdf({ path: 'report.pdf', format: 'A4' });

Replace #report-ready with a selector that actually appears when the desired content is ready. The PDF method’s output and timing should be checked against the site’s own rendering behavior.

Rank #4
Sale
Brother DS-640 Compact Mobile Document Scanner, (Model: DS640)
  • FAST SPEEDS - Scans color and black and white documents a blazing speed up to 16ppm (1). Color scanning won’t slow you down as the color scan speed is the same as the black and white scan speed.
  • ULTRA COMPACT – At less than 1 foot in length and only about 1. 5lbs in weight you can fit this device virtually anywhere (a bag, a purse, even a pocket).
  • READY WHENEVER YOU ARE – The DS-640 mobile scanner is powered via an included micro USB 3. 0 cable allowing you to use it even where there is no outlet available. Plug it into you PC or laptop and you are ready to scan.
  • WORKS YOUR WAY – Use the Brother free iPrint&Scan desktop app for scanning to multiple “Scan-to” destinations like PC, Network, cloud services, Email and OCR. (2) Supports Windows, Mac and Linux and TWAIN/WIA for PC/ICA for Mac/SANE drivers. (3)
  • OPTIMIZE IMAGES AND TEXT – Automatic color detection/adjustment, image rotation (PC only), bleed through prevention/background removal, text enhancement, color drop to enhance scans. Software suite includes document management and OCR software. (4)
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Browser support and installation scope

Playwright supports Chromium, WebKit, and Firefox for browser automation, but browser binaries need to match the Playwright version. The browser guide documents npx playwright install and recommends updating Playwright and reinstalling browsers as versions change.

For Chromium automation through Chrome or Edge, Playwright’s BrowserType API documentation says it works best with the Chromium version bundled with Playwright and does not guarantee compatibility with other browser versions. Separately, Playwright’s MCP PDF Export page says that PDF generation in that MCP tool is Chromium-only. That limitation is specific to the MCP export feature, not a general statement about every Playwright API or binding.

Troubleshooting Playwright website PDFs

  • The PDF does not match the screen layout: PDF generation defaults to print CSS. Call page.emulateMedia({ media: 'screen' }) before page.pdf() if the screen styles are the intended output.
  • Backgrounds or color blocks are missing: Set printBackground: true. If colors still differ, check the page’s print color CSS and the API documentation’s -webkit-print-color-adjust guidance.
  • Content is cut off or scaled unexpectedly: Confirm whether format is overriding width and height, review margins, and check whether the page uses CSS @page. Use preferCSSPageSize: true when its CSS page size should win.
  • The exported page is missing content: Navigation may have completed before the application rendered the content. Wait for a site-specific ready selector or other application readiness signal before calling page.pdf().
  • Playwright cannot launch its browser: Install the browser binaries for your installed Playwright version with npx playwright install. After updating Playwright, update the corresponding browser binaries as well.
  • A Chrome or Edge executable behaves unexpectedly: Playwright documents best compatibility with its bundled Chromium and does not guarantee compatibility with other browser versions.
  • The output file is not where expected: Relative path values resolve from the process’s current working directory. Use an explicit path or check that directory.

Or skip the browser setup

If you only need a screenshot or PDF from a URL, ScreenshotNeo is a website screenshot API and MCP server. One GET request can return a PDF; use the PDF option in the API request. See the ScreenshotNeo API documentation for request parameters.

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 -o shot.webp

For a PDF, set the PDF output option documented by the API. ScreenshotNeo accepts cookie or consent banners like a visitor and removes 60+ known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and responses identify the page verdict and billing status in X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents, including Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots a month without a card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan: 1,000 screenshots a month, no card required.

Further reading

Frequently Asked Questions

How do I print a page with Playwright?

Navigate to the page with Playwright, then call page.pdf(). It generates a PDF using print CSS unless you emulate screen media first.

Can Playwright save a PDF without writing a file?

Yes. Omit the path option and page.pdf() returns a PDF buffer.

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.

Quick Recap

Bestseller No. 1
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Scanner type: Document; Connectivity technology: USB; With Auto Scan Mode, the scanner automatically detects what you're scanning
$75.00
Bestseller No. 3
HP Smart Tank 5101 Ink Tank Printer | 2 Years of Ink Included | All-in-One
HP Smart Tank 5101 Ink Tank Printer | 2 Years of Ink Included | All-in-One
PREMIUM SUPPORT - Strong technical expertise to solve issues faster.; THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.
$161.49

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

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.