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

Use Puppeteer and Chromium when your source is HTML and CSS. Launch a browser, load the document, wait for your application’s data and assets, call page.pdf(), then close the browser in a finally block. Puppeteer uses the browser’s print pipeline, so it executes JavaScript, loads web fonts and applies print CSS instead of trying to approximate a layout with drawing commands.

The recommended Node.js workflow

Install Puppeteer in the project that will generate the files:

npm install puppeteer

Puppeteer downloads a compatible Chromium revision during installation in the usual setup. In a production image or serverless runtime, confirm that a compatible Chromium executable and its system libraries are actually present.

Generate a PDF from an HTML string

This complete ES-module example creates an invoice PDF. The @page rule controls the paper and margins; printBackground: true preserves CSS backgrounds; and break-inside: avoid helps keep a card together.

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.
#1 Best Overall
PDF Converter Ultimate - Convert PDF files into Word, Excel, PowerPoint and others - PDF converter software with OCR recognition compatible with Windows 11 / 10 / 8.1 / 8 / 7
  • Convert your PDF files into Word, Excel & Co. the easy way
  • Convert scanned documents thanks to our new 2022 OCR technology
  • Adjustable conversion settings
  • No subscription! Lifetime license!
  • Compatible with Windows 11, 10, 8.1, 7 - Internet connection required
import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
try {
  const page = await browser.newPage();
  await page.setContent(`
    <!doctype html>
    <html>
      <head>
        <meta charset="utf-8">
        <style>
          @page { size: A4; margin: 18mm; }
          body { font-family: Arial, sans-serif; color: #222; }
          h1 { break-after: avoid; }
          .card { break-inside: avoid; border: 1px solid #ddd; padding: 12px; }
          @media print {
            .screen-only { display: none; }
          }
        </style>
      </head>
      <body>
        <h1>Invoice</h1>
        <p>Rendered from HTML in Node.js.</p>
        <div class="card">Amount due: $240.00</div>
      </body>
    </html>
  `);

  await page.pdf({
    path: 'invoice.pdf',
    format: 'A4',
    printBackground: true,
    margin: { top: '18mm', right: '18mm', bottom: '18mm', left: '18mm' },
  });
} finally {
  await browser.close();
}

page.pdf() returns a Promise<Uint8Array>, so path is optional. You can write the bytes to disk, upload them to object storage, or return them from an HTTP handler.

Generate a PDF from an existing URL

import puppeteer from 'puppeteer';

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

For data-heavy applications, networkidle2 is only a navigation milestone, not proof that your charts or API calls have finished. Wait for an application-specific selector or readiness flag before creating the PDF.

Control media, colors and pagination

Print CSS versus screen CSS

Puppeteer generates PDFs with the print CSS media type. That is normally desirable: you can hide navigation, change columns and create print-only headers. If the PDF must match the screen design, switch media before calling page.pdf():

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

Browsers modify some colors for printing by default. Add this rule when exact colors matter:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Doxillion Free Document Converter – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
  • Convert over 50 document file formats.
  • Preview your files from Doxillion before converting them.
  • Use batch conversion to convert thousands of files at once.
  • Enjoy an easy-to-use, intuitive interface with a Drag and Drop file option.
  • Burn your converted or original files directly to disc.
html {
  -webkit-print-color-adjust: exact;
  print-color-adjust: exact;
}

Use @page { size: A4; margin: 18mm; } or another supported size, and use break-before, break-after and break-inside to influence page boundaries. CSS cannot guarantee that every complex element will fit on one page, so test long tables, images and nested flex or grid layouts.

Wait for fonts, images and application data

page.pdf() waits for fonts by default. External stylesheets, images, web fonts and authenticated resources still need reachable URLs and valid credentials. For deterministic output, wait for your own readiness condition:

await page.goto(url, { waitUntil: 'domcontentloaded' });
await page.waitForSelector('[data-pdf-ready="true"]');
await page.evaluate(() => document.fonts.ready);
await page.pdf({ path: 'ready.pdf', printBackground: true });

If your page does not expose a readiness marker, wait for a known selector, a measured delay, or a request that your application can observe. Avoid using an arbitrary long delay as the only synchronization method: it slows every job and still fails when a backend response is slower than expected.

Return PDF bytes or stream them

Write the returned bytes yourself

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

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

Stream output from a web endpoint

page.createPDFStream() returns a readable stream. In an HTTP server, set the content type and disposition, then pipe the stream to the response. This avoids holding a second full copy of the PDF in application memory, although Chromium still renders the document before and during stream production.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
  • EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
  • READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
  • CREATE, COMBINE, SCAN and COMPRESS PDFs
  • FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs
  • LIFETIME License for 1 Windows PC or Laptop. 5GB MobiDrive Cloud Storage Included.

Puppeteer or PDFKit?

Requirement Puppeteer PDFKit
HTML and CSS fidelity Uses Chromium layout and print CSS Requires drawing and text APIs
JavaScript in the page Executes browser JavaScript Does not render an HTML page
Fonts and web assets Loads browser resources when reachable You position and embed content yourself
Pagination controls @page and CSS break rules Manual layout logic
Streaming createPDFStream() Node.js stream output is central to its API
Deployment footprint Chromium and its libraries Smaller direct-PDF dependency
Best fit Existing HTML/CSS templates Documents constructed from drawing primitives

Choose PDFKit when the document is fundamentally a canvas of positioned text, lines and images. Do not describe PDFKit as an HTML renderer unless you add and verify a separate conversion layer.

Production design and security

Reuse the browser, isolate each job

Launching Chromium for every request adds startup work. A service handling many PDFs can keep one browser process and create a fresh page per job. Always close pages, and close the browser during shutdown. Keep cleanup in finally blocks so navigation errors do not leak tabs or processes.

Make deployment explicit

  • Verify the Chromium executable works in the same container or serverless image used in production.
  • Install the required system libraries and fonts; a development laptop having them does not mean a minimal Linux image does.
  • Set explicit paper size, margins and background behavior rather than relying on defaults.
  • Capture logs and the failing URL or document identifier, but do not log credentials or private HTML.

Treat untrusted HTML as code

A page can execute JavaScript and request network resources. If users supply HTML, isolate rendering, restrict outbound network access, prevent access to cloud metadata and internal services, and never expose application secrets in page globals, cookies or headers unless the renderer is trusted. Sanitize HTML when your threat model requires it; PDF generation is not an HTML security boundary.

Common failures and precise fixes

The PDF is blank or missing dynamic content

Cause: rendering started before client-side data arrived, or the page failed to load an API. Fix: wait for a content-specific selector or readiness marker, inspect browser console and request errors, and verify that the renderer can reach the API with the required authentication.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
  • Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.
  • Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
  • Read & Annotate. Enjoy intuitive reading modes and powerful tools to comment, highlight, and mark up PDFs.
  • Create & Manage PDFs. Create new PDFs, combine multiple files, scan documents, and compress for easy sharing.
  • Fill & Sign Forms. Complete forms and digitally sign documents with secure e-signature tools.

The PDF looks different from the browser

Cause: print media rules, print color adjustment, different viewport dimensions, or missing fonts. Fix: decide whether print or screen styling is the target, call emulateMediaType('screen') when appropriate, set a viewport explicitly, enable printBackground, and make fonts reachable before capture.

Images or web fonts are absent

Cause: blocked cross-origin requests, private URLs, certificate errors, or a race with lazy loading. Fix: use renderer-reachable URLs, provide the necessary authenticated context, wait for the image and document.fonts.ready, and load lazy content before printing.

Navigation times out

Cause: a slow dependency, a never-ending connection, DNS failure or a page waiting on a blocked third-party request. Fix: identify the request that never completes, use an application readiness condition instead of waiting for every connection, and block unnecessary resources where safe. Do not simply increase the timeout without finding the dependency.

Chromium will not start in production

Cause: missing executable, shared libraries, sandbox configuration or incompatible architecture. Fix: use a supported Chromium build for the runtime, install its documented libraries, verify executable permissions and test the exact production image. Avoid disabling the sandbox casually; if your environment requires it, isolate the renderer and apply the platform’s security guidance.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
PDF Pro 3 - PDF editor to create, edit, convert and merge PDFs - 100% Compatible with Adobe Acrobat - for Windows 11, 10, 8.1, 7
  • ALL-IN-ONE SOLUTION – read, edit, convert, merge and protect your PDF files
  • MAXIMUM FUNCIONALITY – create interactive forms, compare PDFs, bates numbering, find and replace text or colors, convert documents, OCR engine, comment, highlight, fill out and print forms, document protection and others
  • EASY TO INSTALL AND USE – well-structured user-interface, in-program instructions, free tech support whenever you need it
  • GREAT VALUE FOR MONEY - why spend a fortune if you can have maximum functionality at a reasonable price - this also fits the requirements of companies very well

Pages break in the wrong places

Cause: content is taller than the available page area or CSS break rules are applied to the wrong ancestor. Fix: set paper and margins explicitly, use break-inside: avoid for cards and rows where practical, and design long tables with repeatable headers and acceptable row splitting.

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 provides a hosted screenshot and PDF API when you do not want to operate Chromium. Its PDF options include paper size, margins, landscape orientation and page ranges, alongside custom JavaScript and CSS, waits, headers, cookies and authorization.

One GET request returns the PDF or image. See the ScreenshotNeo documentation for the current request parameters.

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

Node.js:

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com',
  format: 'pdf'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`ScreenshotNeo request failed: ${res.status}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await Bun.write('page.pdf', bytes);

Python:

import requests
r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com", "format": "pdf"},
    timeout=90,
)
r.raise_for_status()
open("page.pdf", "wb").write(r.content)

ScreenshotNeo accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers. It also offers an MCP server with take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients. The Free plan includes 1,000 screenshots monthly without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

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

FAQ

Does Puppeteer create a PDF from an HTML string without a URL?

Yes. Create a page and pass the string to page.setContent(); external assets still need reachable URLs or embedded data.

Can I return the PDF directly from an Express route?

Yes. Generate bytes or a PDF stream, set Content-Type: application/pdf and a suitable Content-Disposition, then send or pipe the result after rendering completes.

Why does a PDF have a different number of pages after a CSS change?

Pagination depends on the printable content width, margins, font metrics and break rules. A small font or spacing change can move an element across a page boundary.

Quick Recap

Bestseller No. 1
PDF Converter Ultimate - Convert PDF files into Word, Excel, PowerPoint and others - PDF converter software with OCR recognition compatible with Windows 11 / 10 / 8.1 / 8 / 7
PDF Converter Ultimate - Convert PDF files into Word, Excel, PowerPoint and others - PDF converter software with OCR recognition compatible with Windows 11 / 10 / 8.1 / 8 / 7
Convert your PDF files into Word, Excel & Co. the easy way; Convert scanned documents thanks to our new 2022 OCR technology
$29.99
Bestseller No. 2
Doxillion Free Document Converter – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
Doxillion Free Document Converter – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
Convert over 50 document file formats.; Preview your files from Doxillion before converting them.
Bestseller No. 3
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.; CREATE, COMBINE, SCAN and COMPRESS PDFs
$99.99
SaleBestseller No. 4
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.; Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
$74.99
Bestseller No. 5
PDF Pro 3 - PDF editor to create, edit, convert and merge PDFs - 100% Compatible with Adobe Acrobat - for Windows 11, 10, 8.1, 7
PDF Pro 3 - PDF editor to create, edit, convert and merge PDFs - 100% Compatible with Adobe Acrobat - for Windows 11, 10, 8.1, 7
ALL-IN-ONE SOLUTION – read, edit, convert, merge and protect your PDF files
$29.99

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.