October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
HTML to PDF

Best Node.js Libraries for Converting HTML to PDF

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

For HTML that must look like a browser page, use Puppeteer or Playwright. For PDFs whose layout you create directly in code, use PDFKit. If you do not want to operate a browser process, use a hosted HTML-to-PDF API. There is no evidence-based universal winner for speed, cost, or compatibility, so choose according to rendering requirements, deployment model, and the PDF controls your application needs.

Which Node.js approach fits your PDF job?

Approach Best fit What you control Important limitation
Puppeteer Printing an existing web page with Chromium Print or screen CSS, page format, headers and footers, browser actions Requires a browser automation environment; no comparable deployment benchmark is established
Playwright Printing pages when Playwright already powers your automation Print or screen CSS and the project’s browser environment The available sources do not establish output-quality or speed advantages over Puppeteer
PDFKit Generating every PDF element programmatically Drawing, text, images and streams in application code Its documentation does not establish general HTML rendering
Hosted conversion API Teams that prefer a managed browser or remote conversion service Operational model and service integration Security, retention, limits, pricing and reliability must be checked with the provider

Use Puppeteer or Playwright when your source of truth is HTML and CSS. Use PDFKit when the source of truth is data and you can build the document layout yourself. A hosted API is an operational choice rather than a different rendering model; verify how it handles private data, assets and failures before sending production documents.

Generate a PDF from a web page with Puppeteer

Puppeteer’s documented workflow is to navigate to a page and call Page.pdf(). PDF generation uses print CSS. The method waits for fonts by default, which helps avoid capturing text before web fonts load. See the Puppeteer PDF guide, Page.pdf API and PDFOptions reference.

Install and run

npm install puppeteer
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  try {
    const page = await browser.newPage();
    await page.goto('https://example.com', { waitUntil: 'networkidle0' });
    await page.pdf({
      path: 'example.pdf',
      format: 'A4',
      printBackground: true,
      margin: { top: '20mm', right: '15mm', bottom: '20mm', left: '15mm' }
    });
  } finally {
    await browser.close();
  }
})();

Replace the URL with a page your process can access. Use waitUntil: 'networkidle0' when the page’s network activity settles; for applications with long polling or analytics, wait for a specific selector instead so the job does not remain open indefinitely.

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

Print CSS versus screen CSS

Browsers can render a different design for printing. Puppeteer documents page.emulateMediaType('screen') when you want screen media before calling page.pdf():

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

Printing modifies colors by default. When exact colors matter, add this CSS to the page:

* {
  -webkit-print-color-adjust: exact;
  print-color-adjust: exact;
}

Test whether your document should use print styles or screen styles; selecting one can change pagination, visibility and color.

Useful Puppeteer options

  • format: choose a paper format such as A4 or Letter.
  • path: write directly to a file; omit it when you need the returned PDF data.
  • printBackground: include CSS backgrounds.
  • headerTemplate and footerTemplate: define printed headers and footers, including injected page-number and total-page values documented by Puppeteer.
  • preferCSSPageSize: honor CSS @page dimensions when your stylesheet defines them.
  • pageRanges: export selected pages when you do not need the entire document.

Generate a PDF with Playwright

Playwright’s page.pdf() returns a PDF buffer and renders with print CSS. Its API also documents emulating screen media before PDF generation when screen styling is required. Install the package and browser binaries according to the Playwright Page API.

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.
npm install playwright
const { chromium } = require('playwright');
const fs = require('node:fs/promises');

(async () => {
  const browser = await chromium.launch();
  try {
    const page = await browser.newPage();
    await page.goto('https://example.com', { waitUntil: 'networkidle' });
    await page.emulateMedia({ media: 'print' });
    const pdf = await page.pdf({
      format: 'A4',
      printBackground: true,
      margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' }
    });
    await fs.writeFile('example-playwright.pdf', pdf);
  } finally {
    await browser.close();
  }
})();

Playwright is a practical choice when the rest of your tests or automation already uses it. The available documentation does not provide a measured comparison with Puppeteer, so select based on your existing project, browser setup and required API behavior rather than an assumed performance ranking.

Can PDFKit convert HTML?

PDFKit is a JavaScript library for creating PDF documents directly. Its documentation says that, in Node.js, PDFDocument instances are readable streams that can be piped to a file or HTTP response. That makes it suitable when your application owns the layout and can express it as drawing commands. The cited documentation does not establish PDFKit as a drop-in HTML/CSS renderer.

npm install pdfkit
const PDFDocument = require('pdfkit');
const fs = require('node:fs');

const doc = new PDFDocument({ size: 'A4', margin: 50 });
doc.pipe(fs.createWriteStream('invoice.pdf'));
doc.fontSize(20).text('Invoice');
doc.moveDown().fontSize(11).text('Created directly with PDFKit.');
doc.moveDown().text('Total: $125.00');
doc.end();

Because the document is a stream, you can pipe it to an HTTP response instead of a file. You must implement pagination, typography, tables and HTML-to-layout mapping yourself or with additional code. Choose it when deterministic, programmatic composition matters more than reproducing an existing webpage.

Hosted HTML-to-PDF conversion

A hosted service accepts HTML or a URL and returns PDF bytes, avoiding a browser process in your application deployment. One provider documents a Node.js server API and presents local Puppeteer or Playwright when browser automation or on-premises operation is required; those are provider claims, so confirm data handling, limits, pricing and reliability for your workload before adoption.

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

Or skip the browser setup

ScreenshotNeo is a website capture API that can return a PDF from one GET request. It accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page verdict and billing result in X-Page-Verdict and X-Billed headers. It also provides an MCP server with take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.

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

For PDF output, adapt the request with the PDF option described in the ScreenshotNeo documentation. The same service supports full-page capture, lazy-image loading, CSS-selector element capture, custom CSS and JavaScript, click actions, wait conditions, request blocking, headers, cookies, authorization, timezone and geolocation, PDF paper settings, margins, orientation and page ranges, signed links, async jobs, webhooks, bulk capture of up to 100 URLs per call, caching with a chosen TTL, and a usage API.

Use the documented client patterns when integrating from code:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 shots per month without a card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.

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

Decision checklist

  • Choose Puppeteer if you want a documented Chromium print workflow and fine-grained page actions.
  • Choose Playwright if Playwright already runs your browser automation and you want its PDF buffer API.
  • Choose PDFKit if you are generating a new layout from data rather than reproducing HTML.
  • Choose a hosted API if removing browser installation and process management is worth evaluating the provider’s data and service terms.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting PDF generation

Styles or colors are wrong

Check whether print CSS is active. Try emulateMediaType('screen') (Puppeteer) or screen media emulation (Playwright), enable printBackground, and use print-color-adjust when exact colors are required.

Fonts or images are missing

Wait for the relevant selector or network activity instead of capturing immediately. Ensure the browser can reach external assets and that authenticated resources receive the required cookies or headers.

The job never finishes

Pages with analytics, WebSockets or polling may never become idle. Replace a network-idle wait with a meaningful selector, an explicit bounded delay, or application-level readiness signal, and always close the browser in a finally block.

PDFKit output does not match HTML

This is expected when you use a drawing library for browser markup. Either map the layout deliberately in PDFKit or switch to a browser renderer or hosted conversion service.

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

Private pages fail in a hosted service

Confirm whether the service supports authorization headers, cookies and private network access, and review its retention and security terms before sending confidential HTML.

Performance, reliability and cost considerations

The available documentation does not provide a comparable benchmark, browser-size study, compatibility matrix or pricing analysis for Puppeteer, Playwright and PDFKit. Measure your own pages, including asset-heavy and authenticated cases. Reuse a browser process where your deployment permits it, bound navigation and rendering time, and record failures separately from successful PDFs. For a hosted API, measure request latency, retry behavior, data-transfer cost and service limits under your real document mix.

FAQ

Which library converts an existing HTML page most faithfully?

Puppeteer and Playwright are the browser-rendering choices described here. The sources do not establish a universal winner, so test the exact CSS, fonts and JavaScript used by your pages.

Can I use PDFKit with an HTML template?

Not as a general HTML renderer based on the cited documentation. PDFKit creates PDF content programmatically; use a browser renderer when HTML/CSS fidelity is the requirement.

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

Should I use print CSS or screen CSS?

Use print CSS for document-oriented pagination, or explicitly emulate screen media when the PDF must retain the screen design. Validate colors and page breaks in both cases.

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.

Read next

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.