Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

Convert a Webpage to PDF with Playwright in TypeScript

A practical TypeScript guide to creating webpage PDFs with Playwright, including print settings, page sizing, background graphics, and troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Playwright’s Chromium browser to open the page, then call page.pdf(). By default, PDF generation uses print CSS; set printBackground: true to include background graphics, or emulate screen media first if you want the page’s screen styling.

Convert a webpage to PDF with TypeScript

Install Playwright in your project with npm install playwright. The example below uses the documented Playwright APIs to launch Chromium, navigate to a URL, save an A4 PDF, and close the browser even if navigation or PDF generation fails. It is an illustrative combination of the documented APIs, not a claim that this exact snippet was tested.

As an Amazon Associate I earn from qualifying purchases.

import { chromium } from 'playwright';

async function savePageAsPdf(): Promise<void> {
  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();
  }
}

await savePageAsPdf();

page.goto() navigates the page to the target URL. page.pdf() writes the PDF to the supplied path; it also returns a PDF Buffer, which you can use instead when the output should be handled by your application rather than saved directly. See the Playwright Pages guide and the Page API reference.

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.

Choose print or screen styling

Use print CSS for a print-oriented document

page.pdf() renders using print CSS media by default. That can produce a different layout from the page shown in a browser tab because sites often define separate print styles.

Use screen CSS when you want the on-screen appearance

Emulate screen media before calling page.pdf() when the PDF should use screen styles:

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

This changes the media style used for rendering; it does not guarantee that the PDF will fit on one page or preserve every screen interaction. The default and media behavior are documented in the Page API reference.

Set page size, margins, backgrounds, and pagination

Start with only the options that answer a real layout need. The API supports these controls:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Need Option What to know
Choose common paper size format Accepts named formats such as A4 and Letter. When supplied, it takes precedence over width and height.
Set exact dimensions width, height Dimensions accept px, in, cm, or mm; a value without a unit is interpreted as pixels.
Honor the page’s CSS size preferCSSPageSize Use this when CSS @page sizing should take precedence over API-provided size settings.
Include background graphics printBackground Defaults to false. Set to true to print background graphics.
Change orientation or whitespace landscape, margin Choose landscape orientation and margins appropriate to the document.
Scale the rendered page scale The documented range is 0.1 to 2.
Export selected pages pageRanges Use page ranges when only part of a longer document is needed.
Add page furniture or structure displayHeaderFooter, templates, outline, tagged Configure headers/footers or request an outline or tagged PDF where appropriate.

For example, this saves an A4 PDF with backgrounds and landscape orientation:

await page.pdf({
  path: 'page.pdf',
  format: 'A4',
  landscape: true,
  printBackground: true,
  margin: { top: '12mm', right: '12mm', bottom: '12mm', left: '12mm' }
});

Background graphics and exact CSS colors are separate concerns: setting printBackground includes background graphics, but PDF colors are modified for printing by default. The API points to the CSS property -webkit-print-color-adjust for exact color rendering. Validate the output if color fidelity matters. Header and footer templates have limitations: scripts are not evaluated, and page styles are not visible inside the templates. Refer to the current Page API reference for option details.

Return the PDF buffer instead of saving a file

Omit path to receive the generated PDF as a buffer and pass it to the next step of your application, such as storage or a response handler:

const pdfBuffer = await page.pdf({ format: 'A4' });

The returned value is a PDF Buffer, as documented by Playwright. Choose this form when your application needs to control what happens to the bytes; use path for a direct local file.

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

Handle common PDF problems

  • Backgrounds are missing: printBackground defaults to false. Set it to true if background graphics should appear.
  • The PDF looks different from the browser tab: PDF output defaults to print media. Call page.emulateMedia({ media: 'screen' }) before page.pdf() if screen CSS is the desired presentation.
  • The page size is not what you expect: When format is set, it takes precedence over width and height. To let CSS @page sizing take precedence, use preferCSSPageSize.
  • Colors look muted or altered: Printing modifies PDF colors by default. Background inclusion and exact color rendering are different settings; review printBackground and the documented -webkit-print-color-adjust guidance.
  • A header or footer is missing page-specific styling or script output: Header/footer templates do not see page styles, and scripts in templates are not evaluated.
  • The file was not written: Check that the process can write to the requested path and that browser.close() is reached only after page.pdf() completes. The example uses try/finally so browser cleanup occurs on errors.
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 PDF from one GET request. For parameters and response details, see the ScreenshotNeo documentation.

curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://stripe.com 
  -o page.pdf 
  -d format=pdf

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are never billed. It also has an MCP server so AI agents can take screenshots. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Visit ScreenshotNeo or sign up free for 1,000 screenshots a month with no card.

Sources and support scope

The Playwright documentation says page.pdf() generates a PDF using print CSS media. A separate page for the Playwright MCP PDF Export tool says PDF generation there is Chromium-only; that statement applies to that MCP tool and is not a complete browser-support statement for every use of page.pdf(). The reviewed Page API reference does not establish a full browser-support matrix, so check its current documentation for the support details relevant to your Playwright version.

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.

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

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

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.