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.

Use Playwright’s Chromium browser and page.pdf() to turn a local HTML page into a PDF. The method works with a local file:// URL or a local web server; choose print or screen media deliberately, set paper size and margins, and wait for any application-specific assets before generating the file.

Convert a local HTML file to PDF with Playwright

Playwright’s page.pdf() generates a PDF using print CSS media by default. PDF generation is documented for Chromium, so launch Chromium rather than assuming the same behavior across browser engines. The example below saves the PDF to disk and enables background graphics.

1. Install Playwright and its browser

In a new Node.js project, install the package and its Chromium browser binary:

npm init -y
npm install playwright
npx playwright install chromium

Playwright requires browser binaries in addition to the package. See the browser installation guide for browser setup details, including headless-shell options for CI.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

2. Create the PDF

Save this as html-to-pdf.js. Change the file URL to the absolute path of your HTML file. On Windows, use a valid file URL, for example file:///C:/work/document.html.

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

(async () => {
  const browser = await chromium.launch();
  try {
    const page = await browser.newPage();
    await page.goto('file:///absolute/path/to/document.html', {
      waitUntil: 'load'
    });

    await page.pdf({
      path: 'output.pdf',
      format: 'A4',
      printBackground: true,
      preferCSSPageSize: true
    });
  } finally {
    await browser.close();
  }
})();

Run it with node html-to-pdf.js. Playwright writes output.pdf and also returns the generated PDF as a buffer. The Page API documentation describes the available PDF options.

Choose a local file or local HTTP server

A file:// URL is convenient for a self-contained static document. Use a local HTTP server instead when the page relies on relative URLs, JavaScript modules, application routes, or server-side behavior. For example, run your project’s development server and navigate to its local URL:

await page.goto('http://127.0.0.1:3000/document', {
  waitUntil: 'load'
});

Neither navigation mode guarantees that every application-specific asynchronous task, web font, or external image is ready when PDF generation starts. Wait for the page state your application needs before calling page.pdf(); there is no universal Playwright wait that can infer when every document is finished.

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.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Control print and screen styling

By default, page.pdf() renders using print CSS media. This means @media print rules apply and screen-only styling may not appear. If you need the PDF to follow screen styles, explicitly switch media before generating it:

await page.emulateMedia({ media: 'screen' });
await page.pdf({ path: 'output.pdf', printBackground: true });

To use print styles, leave the media mode at its default or explicitly select print. Choose the mode that matches the document you intend to deliver; changing it can affect layout, visibility, and page breaks.

Set paper size, margins, scale, and page ranges

Use format for a standard paper size such as A4 or Letter. Alternatively, specify width and height with units such as px, in, cm, or mm. When both are provided, format takes priority over width and height.

If the document’s CSS defines an @page size and that definition should control the PDF, set preferCSSPageSize: true. This tells Chromium to prefer the CSS page size over scaling the content to the paper size selected in the PDF options.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
await page.pdf({
  path: 'selected-pages.pdf',
  format: 'Letter',
  margin: {
    top: '20mm',
    right: '15mm',
    bottom: '20mm',
    left: '15mm'
  },
  pageRanges: '1-3',
  scale: 1,
  printBackground: true
});

Margins reserve space around the printable content. pageRanges limits output to selected pages. The default scale is 1; supported values run from 0.1 through 2. Check the generated file after changing scale, since scaling can alter the fit and readability of content.

Let CSS define the page

For a document whose page dimensions belong in its stylesheet, use an @page rule and enable CSS page sizing:

/* document.css */
@page {
  size: A4;
  margin: 18mm;
}
await page.pdf({
  path: 'output.pdf',
  preferCSSPageSize: true,
  printBackground: true
});

A CSS page size is useful when the same print stylesheet should govern browser printing and Playwright output. If you specify a PDF format as well, remember that CSS sizing is only preferred when preferCSSPageSize is enabled.

Keep background graphics and colors

Background graphics are disabled by default. Set printBackground: true to include them, such as colored panels or background images. Chromium also applies print-oriented color adjustments. If exact colors matter, the Page API notes that CSS -webkit-print-color-adjust can be used to request more faithful color rendering:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
html {
  -webkit-print-color-adjust: exact;
}

Use this alongside printBackground: true when appropriate, then inspect the resulting PDF. A CSS color-adjustment rule does not replace the PDF option that enables backgrounds.

Add headers and footers

Set displayHeaderFooter: true to print a header, footer, or both. Templates can include documented classes for injected values such as the date, title, URL, page number, and total page count.

await page.pdf({
  path: 'output.pdf',
  displayHeaderFooter: true,
  headerTemplate: '<div style="font-size:9px;width:100%;text-align:center">Document</div>',
  footerTemplate: '<div style="font-size:9px;width:100%;text-align:center"><span class="pageNumber"></span> / <span class="totalPages"></span></div>',
  margin: { top: '20mm', bottom: '20mm' }
});

Header and footer templates have important limits: scripts inside them are not evaluated, and the page’s styles are not visible inside the templates. Include the styling the template needs directly in its markup, and reserve enough margin for the header or footer to fit.

Wait for dynamic content before printing

Navigation reaching the load state is not proof that every application task or remote asset is complete. Add an explicit readiness check that reflects your page. For example, if your application marks the document ready with a known element, wait for that selector:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
await page.goto('http://127.0.0.1:3000/document', {
  waitUntil: 'load'
});
await page.locator('[data-pdf-ready="true"]').waitFor();
await page.pdf({ path: 'output.pdf', format: 'A4', printBackground: true });

For a page that depends on web fonts, you can also wait for the browser’s font-loading promise before printing:

await page.evaluate(() => document.fonts.ready);
await page.pdf({ path: 'output.pdf', format: 'A4' });

Use a readiness signal owned by the application for data or rendering that has no reliable browser-wide completion event. For external images and other assets, check that the page can access them and verify the final PDF rather than treating a generic navigation state as a guarantee.

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

Save the file or consume the PDF buffer

When you pass path, Playwright saves the PDF to that path. The call also returns a buffer, which is useful when the PDF should be uploaded, returned from a service, or processed without first writing a local file:

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

// Example: write the returned buffer yourself.
const fs = require('node:fs/promises');
await fs.writeFile('output.pdf', pdfBuffer);

Choose one output flow based on what the rest of your program needs. A path is straightforward for a command-line conversion; the buffer gives your application direct access to the generated PDF bytes.

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

Common problems and fixes

  • Chromium will not launch: install the browser binary for the installed Playwright package with npx playwright install chromium. In CI, consult Playwright’s browser guide for the supported setup rather than relying on an arbitrary system browser.
  • Relative images or scripts are missing: check whether the document expects a web server or a different working directory. Serve the page locally and navigate to its HTTP URL if file-relative loading is unsuitable.
  • The PDF has no background colors or images: set printBackground: true. Background graphics are off by default.
  • The PDF looks like print layout instead of the browser: this is the default. Call page.emulateMedia({ media: 'screen' }) before page.pdf() if screen styles are intended.
  • The page size does not match CSS @page: set preferCSSPageSize: true. If you also set format, it takes priority over width and height; review which sizing mechanism should control the output.
  • Fonts, images, or application content are missing: wait for the relevant application readiness signal or asset before printing. A successful navigation does not establish that every asynchronous dependency has finished.
  • Header or footer content is blank or unstyled: template scripts are not evaluated, and page styles are not inherited by the templates. Put needed markup and styling in the template itself and allow space with PDF margins.
  • Colors differ from the screen: PDF output uses print media by default and Chromium applies print color adjustments. Confirm the intended media mode, enable backgrounds, and consider -webkit-print-color-adjust for exact color requests.

Or skip the browser setup

If you need a screenshot or PDF from a publicly accessible page rather than a local Playwright workflow, ScreenshotNeo offers a single-request API and an MCP server for AI agents. Cookie banners are accepted and removed before capture, along with known newsletter popups and chat widgets; bot checks, blank pages, and failed loads are not billed. You can also use the MCP tools from Claude, Cursor, or another MCP client. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000.

Here is the one-call request for an image capture:

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 API documentation for PDF options and request parameters. ScreenshotNeo can return an image or PDF for a web URL; it is not a replacement for rendering a local file that is unavailable to the service. Learn more at ScreenshotNeo, or sign up free for 1,000 screenshots a month with no card.

Frequently Asked Questions

Can I generate a PDF from a local HTML file without hosting it?

Yes. Navigate Chromium to a valid absolute file:// URL. A local HTTP server is often more suitable when the page depends on routes, modules, or relative assets.

Does Playwright use screen or print CSS for PDFs?

It uses print CSS media by default. Call page.emulateMedia({ media: 'screen' }) first if the PDF should use screen styles.

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

Can I make the PDF follow a CSS @page size?

Yes. Set preferCSSPageSize: true in page.pdf().

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.