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

For HTML that relies on browser layout, CSS, or web fonts, convert it to PDF in Node.js with a headless browser. Puppeteer and Playwright both provide a page.pdf() method: load a URL or set page content, choose print or screen media, generate the PDF, and close the browser. Use PDFKit when you want to build PDF content programmatically; the cited PDFKit guide does not document it as an HTML renderer.

Choose the right Node.js approach

A headless browser is the practical choice when your input is a web page or HTML document and you need the browser to lay out its CSS. Puppeteer and Playwright both expose PDF generation from a page, with print media as the default. Their APIs and controls differ slightly, but both require a browser runtime in the environment that runs your code.

Approach Best fit PDF and rendering controls Runtime consideration
Puppeteer Browser-rendered HTML, using Puppeteer’s page API. page.pdf() writes a PDF; print CSS is the default. Use emulateMediaType('screen') for screen styles. Launch a browser and ensure the runtime can run it. Puppeteer’s documentation version surfaced for this guidance is 25.12.0.
Playwright Browser-rendered HTML when Playwright’s page API suits your project. page.pdf() returns a buffer; print CSS is the default. Screen media can be selected, and width and height accept px, in, cm, or mm. Launch a browser and ensure the runtime can run it.
PDFKit Programmatic construction of PDF content rather than browser layout of existing HTML. The official guide shows creating a PDFDocument and piping it to a writable Node stream; it does not establish HTML rendering. Uses a writable stream in the documented workflow; this is not a substitute for browser-based HTML rendering.

Convert a URL to PDF with Puppeteer

Install Puppeteer in your Node.js project, then save this as an ES module such as url-to-pdf.mjs. The flow launches a browser, opens a page, navigates to the target, writes the PDF, and closes the browser even if an operation fails.

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: 'page.pdf', format: 'A4', printBackground: true });
} finally {
  await browser.close();
}

Run it with node url-to-pdf.mjs. The output path is relative to the process’s current working directory unless you provide an absolute path. page.pdf() waits for fonts by default, according to Puppeteer’s documentation. The example requests networkidle2 before printing; for a page with ongoing network activity, choose a readiness condition appropriate to that site rather than assuming all requests will become idle.

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.

Use print styles or screen styles

PDF generation uses print CSS media by default. That is usually appropriate for a document intended to be printed: the site’s @media print rules can simplify navigation and adjust page layout. If the PDF should resemble the on-screen page, emulate screen media before calling pdf():

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

Browsers may adjust colors for print output. Puppeteer documents -webkit-print-color-adjust for retaining exact colors. Add it to the page’s stylesheet when exact color rendering matters, then inspect the resulting PDF because the page’s print styles and browser rendering both affect the final document.

Convert an HTML string

For generated or locally assembled markup, set content on a page instead of navigating to a URL. Ensure referenced stylesheets, images, and fonts are available to the browser; relative paths need a meaningful base URL or absolute paths.

import puppeteer from 'puppeteer';

const html = `<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    body { font: 16px sans-serif; margin: 24px; }
    h1 { color: #173b65; }
    @media print { .screen-only { display: none; } }
  </style>
</head>
<body>
  <h1>Quarterly report</h1>
  <p>Generated from HTML in Node.js.</p>
</body>
</html>`;

const browser = await puppeteer.launch();
try {
  const page = await browser.newPage();
  await page.setContent(html, { waitUntil: 'load' });
  await page.pdf({ path: 'report.pdf', format: 'A4', printBackground: true });
} finally {
  await browser.close();
}

This example uses inline CSS, so no external asset path is required. If you inject untrusted HTML, treat it as untrusted input: rendering it in a browser is not the same as sanitizing it or making it safe to load.

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.

Use Playwright instead

Playwright also generates PDFs from a page and returns the PDF as a buffer. Install Playwright and its browser runtime for your environment, then save this example as playwright-pdf.mjs:

import { chromium } from 'playwright';
import { writeFile } from 'node:fs/promises';

const browser = await chromium.launch();
try {
  const page = await browser.newPage();
  await page.goto('https://example.com', { waitUntil: 'networkidle' });
  const pdf = await page.pdf({ format: 'A4', printBackground: true });
  await writeFile('page.pdf', pdf);
} finally {
  await browser.close();
}

To use screen styles, call await page.emulateMedia({ media: 'screen' }) before page.pdf(). Playwright documents width and height in px, in, cm, or mm, and paper formats including Letter and A4. For example, specify dimensions directly with page.pdf({ width: '210mm', height: '297mm' }) when a custom page size is more suitable than a named format.

Choose between the two browser libraries based on the APIs already used in your project and the controls you need. Both still depend on a browser-capable runtime; selecting a library does not remove that deployment constraint.

Set page size, margins, and output details

For standard paper, pass a named format such as A4 or Letter in the PDF options. For custom dimensions, Playwright explicitly documents px, in, cm, and mm units for width and height. Set margins and other print options through the PDF method’s options supported by the browser library version you install; consult its API documentation for exact option names and behavior.

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.
  • Backgrounds: set printBackground: true when background colors or images must appear in the output.
  • Print versus screen: keep the default print media for print-specific layout; emulate screen media before PDF generation if the screen stylesheet is the intended output.
  • Color: print output may adjust colors. Puppeteer documents -webkit-print-color-adjust as the CSS mechanism for retaining exact colors.
  • Long pages: browser pagination and print CSS determine page breaks. Use print-specific CSS to manage breaks and verify the final PDF for clipped or split content.

Run browser PDF generation in production

The application must be able to launch the browser used by the library. Before deploying, confirm that the chosen Node.js runtime can run that browser and that the browser executable is present and accessible. The documentation cited here does not establish exact memory, CPU, hosting, or security requirements for a particular deployment, so validate those against your own HTML, workload, and provider.

  • Close browser resources: close pages or contexts when no longer needed and always close the browser in a finally block, as in the examples.
  • Bound work: set an application-level timeout for navigation and PDF jobs so a page that never finishes cannot occupy a worker indefinitely.
  • Handle concurrency deliberately: browser rendering consumes runtime resources. Measure your own workload before choosing parallelism or worker sizing; no performance benchmark is established here.
  • Check output: confirm the file exists, is non-empty, and opens as a PDF. For buffer-based output, write the returned buffer and handle filesystem errors.
  • Protect inputs: if users can submit URLs or HTML, apply your own input validation and access controls. The cited PDF-generation guides do not define an application security policy.

Troubleshoot common conversion failures

The browser will not launch

The runtime may not have a compatible browser available or may prevent the process from launching it. Install or provision the browser required by your library and verify the executable and permissions in the same environment that runs the Node.js service.

The PDF is blank or missing content

The page may not have finished rendering before the PDF call. Wait for a relevant load condition or for a page-specific selector that signals the content is ready. If content appears only after client-side scripts run, allow those scripts to complete before printing.

Fonts or images are absent

Check that asset URLs are reachable from the browser process and that relative URLs resolve from the page’s base location. Puppeteer waits for fonts by default during page.pdf(); that does not guarantee an inaccessible font can load. Inspect browser errors and network access for failed assets.

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

Colors or layout differ from the browser view

Print CSS is the default for both APIs. If you want the screen design, switch to screen media before making the PDF. If print colors are being adjusted, review Puppeteer’s documented -webkit-print-color-adjust guidance and inspect the output against your print stylesheet.

The process hangs on a page

Some sites keep network connections open or continue making requests. A network-idle condition may therefore be a poor readiness signal. Use a more specific readiness condition, such as a selector for the content you need, and enforce a timeout in your application.

The PDF is cut off or paginated badly

Check the chosen page format and dimensions, then review the page’s print stylesheet for fixed widths, overflow, and page-break behavior. Browser PDF pagination follows the rendered document; it cannot infer where your application considers a logical section to begin.

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

Or skip the browser setup

If you need a screenshot rather than a PDF, ScreenshotNeo returns PNG, JPEG, or WebP from one GET request. It is not a replacement for the Puppeteer or Playwright PDF workflow shown above. A screenshot is useful when an image of a page is sufficient; use browser PDF generation when you need a paginated PDF document.

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.

Example request and options are documented at ScreenshotNeo docs:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
  • Cookie banners are accepted and removed before capture; more than 60 known consent platforms, newsletter popups, and chat widgets can be removed, and each step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; responses report the page verdict and billing status in headers.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients.
  • The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

When PDFKit makes more sense

Use PDFKit when you want to construct a PDF directly in code rather than reproduce a browser-rendered HTML page. Its official guide shows creating a PDFDocument and piping it to a writable Node stream. That workflow supports programmatic PDF generation, but the cited guide does not show HTML rendering; choose a headless browser if your requirement is to convert existing HTML and CSS into a PDF.

Frequently Asked Questions

Does Puppeteer save a PDF to a file or return data?

The Puppeteer example uses page.pdf({ path: 'page.pdf' }) to write a file. Playwright’s documented method returns a buffer, which the example writes with Node’s filesystem API.

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.

Can I generate a PDF from HTML without a URL?

Yes. Set the markup on a browser page with Puppeteer’s page.setContent(), wait for required resources, then call page.pdf().

Is PDFKit an HTML-to-PDF converter?

The official PDFKit guide cited here documents programmatic PDF construction and streaming, not HTML rendering.

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.