October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

How to Generate PDFs and Screenshots with Browser APIs

Use window.print() for a visitor-controlled print dialog; use Puppeteer or Playwright to generate PDFs and screenshots in code. Configure media styles and capture scope for the result you need.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use window.print() when a person should choose a printer or save the page as a PDF through the browser dialog. Use Puppeteer or Playwright when code must create a PDF file or capture screenshot bytes without user interaction. Print CSS controls the PDF’s printed layout; screenshot options control image format and capture scope.

Choose the browser API that matches the output

Need Use What it produces
A person chooses a printer or “Save as PDF” window.print() Opens the browser’s print dialog; the browser and user handle the destination.
Code creates a PDF without a dialog Puppeteer page.pdf() or Playwright page.pdf() PDF output as a file or buffer, depending on the API and options.
Code captures the rendered page as an image Puppeteer page.screenshot() or Playwright page.screenshot() Image bytes or a saved image; scope may be viewport-only or full-page.

These are different workflows, not interchangeable ways to call a single browser “export” function. MDN describes window.print() as opening the print dialog for the current document: MDN Window.print().

As an Amazon Associate I earn from qualifying purchases.

Let a visitor print or save the page

Call window.print() in response to a clear user action. It returns undefined, waits for the document to finish loading if needed, and blocks while the print dialog is open. The page cannot use this call to receive PDF bytes or silently select the user’s printer or PDF destination.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<button type="button" onclick="window.print()">Print or save as PDF</button>

Prepare a print-specific layout with CSS

Use @media print to hide navigation, dialogs, and controls that do not belong on paper. Keep content readable in grayscale and avoid relying on hover or interactive states. The @page rule can set page dimensions, orientation, and margins. Browser support and exact rendering can vary, so inspect the result in the browsers you support.

@media print {
  nav,
  .dialog,
  .print-control {
    display: none !important;
  }

  body {
    color: #000;
    background: #fff;
    font-size: 12pt;
  }

  a {
    color: inherit;
    text-decoration: underline;
  }
}

@page {
  size: A4 portrait;
  margin: 18mm;
}

MDN documents @media print and @page for print styling and page geometry: MDN: Printing.

Use print events only for temporary content changes

beforeprint and afterprint fire around a print workflow. They can temporarily adjust content, then restore it, but for ordinary layout changes MDN recommends CSS print rules where possible. For example, if an application must expose a print-only summary, use the events sparingly and ensure restoration works if the print flow is canceled: beforeprint and afterprint.

Generate a PDF with browser automation

Use a real browser automation runtime when a server, build task, or test needs a PDF artifact without a visitor operating a dialog. The examples below assume a page has already been launched and navigated to the target URL. Consult the API reference for the version installed in your project; option availability and output details are version-sensitive.

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

Puppeteer

Puppeteer’s page.pdf() uses print CSS by default. To render using screen media instead, set the media type before generating the PDF. The method can save to a path or return output according to the installed version and options.

const browser = await puppeteer.launch();
try {
  const page = await browser.newPage();
  await page.goto('https://example.com', { waitUntil: 'networkidle2' });
  // Omit this line to use the default print media styles.
  await page.emulateMediaType('screen');
  await page.pdf({ path: 'page.pdf', format: 'A4', printBackground: true });
} finally {
  await browser.close();
}

Remove emulateMediaType('screen') when the document should use its print stylesheet. Puppeteer notes that PDF colors are adjusted for printing by default; its documentation discusses -webkit-print-color-adjust when exact colors matter. Also verify paper format, width and height, margins, background printing, and path/buffer behavior in your installed version: Puppeteer Page.pdf().

Playwright

Playwright’s page.pdf() returns a PDF buffer and uses print CSS. Call page.emulateMedia({ media: 'screen' }) first if the output should use screen styling.

const { chromium } = require('playwright');
const browser = await chromium.launch();
try {
  const page = await browser.newPage();
  await page.goto('https://example.com', { waitUntil: 'networkidle' });
  // Omit this line to use the default print media styles.
  await page.emulateMedia({ media: 'screen' });
  const pdf = await page.pdf({ format: 'A4', printBackground: true });
  await require('node:fs/promises').writeFile('page.pdf', pdf);
} finally {
  await browser.close();
}

See Playwright’s documented PDF options for page size, margins, and print-color behavior: Playwright Page.pdf().

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.

Capture a screenshot with browser automation

For a screenshot, use the screenshot method rather than PDF generation. Decide whether the output should cover the viewport or the full scrollable page, and set the viewport and device scale deliberately if pixel dimensions matter.

Puppeteer screenshot

const browser = await puppeteer.launch();
try {
  const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
  await page.goto('https://example.com', { waitUntil: 'networkidle2' });
  await page.screenshot({ path: 'page.png', fullPage: true });
} finally {
  await browser.close();
}

Puppeteer’s screenshot API supports base64-string and byte-array return forms as well as file output; check the overload matching your installed version: Puppeteer Page.screenshot().

Playwright screenshot

const { chromium } = require('playwright');
const browser = await chromium.launch();
try {
  const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
  await page.goto('https://example.com', { waitUntil: 'networkidle' });
  await page.screenshot({ path: 'page.png', fullPage: true });
} finally {
  await browser.close();
}

Playwright’s default screenshot covers the viewport. Set fullPage: true to capture the full scrollable page. Confirm device scale, viewport, supported formats, and exact output dimensions in the API version you use: Playwright Page.screenshot().

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

Choose print CSS, screen CSS, or screenshot scope intentionally

  • Printed PDF: use print media when the PDF should read like a paper document, with navigation removed and page breaks considered.
  • Screen-styled PDF: emulate screen media before PDF generation when preserving the web layout is the goal.
  • Viewport screenshot: capture the visible region for a browser-state preview or visual check.
  • Full-page screenshot: request the full scrollable document when the whole page is required. Long or dynamically loaded pages may need additional waiting or scroll handling.
  • Exact colors or dimensions: set output options explicitly and validate them in the browser/version used for production. Print color adjustment and page geometry can affect results.

Runtime, reliability, and troubleshooting

Wait for the content you actually need

A navigation completion condition does not guarantee every lazy-loaded image or client-rendered section is ready. If captures are missing content, wait for a specific selector or application-ready signal before producing the artifact. Avoid relying on an arbitrary delay as the only readiness check when the page exposes a reliable condition.

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

Common failures and fixes

  • Calling window.print() but expecting a file or buffer: it opens a user-facing dialog. Use Puppeteer or Playwright PDF generation for automated output.
  • PDF layout differs from the browser view: PDF generation defaults to print media in both tools. Remove print-only layout assumptions by emulating screen media, or adjust the print stylesheet if print output is intended.
  • PDF backgrounds or colors are missing: enable background printing where supported and account for browser print color adjustment; check the relevant API documentation and CSS.
  • Screenshot cuts off below the fold: request full-page capture rather than the default viewport capture.
  • Blank or incomplete capture: wait for the relevant content or selector, and check whether the page requires authentication, interaction, or additional client-side loading.
  • Unexpected dimensions: set the viewport and device scale, then verify the screenshot or PDF options against the installed framework version.
  • Automation behaves differently across browsers: validate against the browser engines and versions you deploy. The cited APIs do not establish identical behavior across every browser/version.

Deployment considerations

Browser automation requires a compatible browser runtime and enough resources for page rendering. Reuse a browser process where appropriate, close pages and browsers reliably, and bound navigation and capture waits so one stalled page does not hold a job indefinitely. For cross-browser testing, BrowserStack documents support for Puppeteer and Playwright, but it is a hosted testing service, not the PDF or screenshot API itself: BrowserStack support FAQ.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server for developers. One GET request returns a PNG, JPEG, WebP, or PDF; its API documentation covers request options.

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

ScreenshotNeo accepts consent banners like a visitor and removes more than 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 response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf 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. Every feature is on every plan. Sign up for free and get 1,000 screenshots a month with no card.

Frequently Asked Questions

Does BrowserStack support Puppeteer?

BrowserStack documents support for Puppeteer and Playwright testing; it is a hosted testing service rather than the capture API itself.

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.

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
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.