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

Use a headless Chromium page and Puppeteer’s page.pdf() method. Put your HTML in a page, wait for its fonts and other assets, choose print or screen CSS, then save the returned PDF bytes. Puppeteer uses the print CSS media type by default, so the result follows print rules unless you explicitly emulate screen media.

What you need before converting HTML to PDF

  • Node.js and a project in which you can install Puppeteer.
  • The HTML string or a URL that the browser can load.
  • Any images, stylesheets and web fonts referenced by the HTML. A browser must be able to reach remote assets, or you should embed them.
  • A writable destination for the PDF, unless you plan to process the returned bytes in memory.

Install Puppeteer in a new project with:

npm install puppeteer

Puppeteer launches Chromium, so your deployment also needs permission to start a browser process and enough temporary storage for the browser and generated files. Treat those as deployment requirements rather than PDF settings.

Convert an HTML string directly

The following complete script loads an HTML string, waits for the document’s fonts, and writes an A4 PDF. page.setContent() is useful when the source is text rather than a public URL.

const puppeteer = require('puppeteer');

const html = `<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Invoice</title>
  <style>
    @page { size: A4; margin: 18mm; }
    body { font-family: Arial, sans-serif; color: #222; }
    h1 { color: #1457a6; }
    .total { margin-top: 24px; font-weight: 700; }
  </style>
</head>
<body>
  <h1>Invoice 1042</h1>
  <p>Generated from an HTML string.</p>
  <p class="total">Total: $125.00</p>
</body>
</html>`;

(async () => {
  const browser = await puppeteer.launch();
  try {
    const page = await browser.newPage();
    await page.setContent(html, { waitUntil: 'networkidle0' });
    await page.evaluate(() => document.fonts.ready);
    await page.pdf({
      path: 'output.pdf',
      format: 'A4',
      printBackground: true,
      margin: { top: '18mm', right: '18mm', bottom: '18mm', left: '18mm' },
      preferCSSPageSize: true
    });
  } finally {
    await browser.close();
  }
})();

Run it with node convert.js. The path option saves the file. The PDF method also returns the PDF bytes, so an application can send them in an HTTP response or store them in object storage instead of writing a local file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Epson EcoTank ET-2800 Wireless Color All-in-One Supertank Printer - Black
  • INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
  • COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
  • ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
  • HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs

Convert an existing web page

For a URL, use page.goto() before calling page.pdf(). This follows Puppeteer’s documented workflow:

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: 'output.pdf' });
  } finally {
    await browser.close();
  }
})();

The guide says PDF generation waits for fonts by default. Waiting for network activity before the call is still useful when your page loads images, stylesheets or application data asynchronously.

Choose print CSS or screen CSS

page.pdf() generates a PDF with the print CSS media type by default (Puppeteer API reference). That means rules inside @media print apply, while screen-only layout rules may not. To reproduce the screen design instead, emulate screen media before creating the PDF:

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

If you do not call emulateMediaType('screen'), leave the page in its default print mode and define the intended print layout in your CSS. Print rendering can modify colors. When exact color output matters, the API documentation points to -webkit-print-color-adjust; for example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
@media print {
  * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
}

Color management still depends on the browser and viewing or printing software, so inspect a generated sample rather than assuming a screen pixel will be identical on paper.

Rank #2
Sale
Epson EcoTank Photo ET-8550 Wireless Wide-Format All-in-One Tank Printer
  • CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
  • INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
  • PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
  • ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴

PDF options that control layout and output

The current PDFOptions reference is version-sensitive. Check it against the Puppeteer version installed in your project. These are the settings most often needed for HTML documents:

Option What it controls Important behavior
format Named paper size such as A4 or Letter When supplied, it takes priority over width and height.
width, height Custom page dimensions Use these when a named format does not match your document.
preferCSSPageSize Whether CSS @page sizing wins When true, an @page size takes precedence over API format or dimensions.
landscape Page orientation Set true for wide tables, diagrams or presentations.
margin Top, right, bottom and left whitespace Use CSS units such as mm, in or px.
printBackground Background colors and images Defaults to false; set true when backgrounds are part of the design.
displayHeaderFooter, headerTemplate, footerTemplate Printed headers and footers Templates are optional; enable the display flag when using them.
pageRanges Pages to include Useful for exporting selected pages instead of the complete document.

Do not set conflicting sizing rules without a reason. For example, choose either an API paper format or CSS-driven page sizing and verify which one your installed version gives priority to. Keep a test document containing long text, a table and a page break so layout changes are visible after upgrades.

Make the HTML PDF-friendly

Define a page model

Use @page for paper size and margins when the document owns its print design. Add explicit break rules around sections that must start on a new page. Avoid relying on a viewport width alone; PDF pagination is controlled by paper dimensions and margins.

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

Load fonts and images deliberately

Remote assets can be unavailable from a server, require authentication, or finish after the initial navigation. Prefer absolute URLs, embed critical images as data URLs, or wait for an application-specific selector before calling page.pdf(). The documented PDF method waits for fonts, but your own asynchronous data and images may need separate readiness checks.

Use print-only and screen-only rules

Hide navigation, cookie controls and interactive buttons in @media print. If the PDF must match a dashboard’s screen appearance, call emulateMediaType('screen') and enable printBackground. If it is intended for physical printing, stay with print media and design for the chosen paper size.

Rank #3
HP Smart Tank 5000 Wireless All-in-One Ink Tank Printer, Scanner, Copier with 2 Years of Ink Included, Best-for-Home, Cartridge-Free, Refillable and AI-Enabled. (5D1B6A)
  • SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
  • INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
  • KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
  • PREMIUM SUPPORT - Strong technical expertise to solve issues faster
  • THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.

Return bytes from a service

Instead of supplying path, capture the return value:

const pdfBytes = await page.pdf({ format: 'A4', printBackground: true });
// Send pdfBytes with Content-Type: application/pdf in your HTTP handler.

The API describes the return value as PDF data. Keep the browser open only as long as needed, and always close it in a finally block so failed jobs do not leave orphaned processes.

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

Common failures and fixes

  • PDF has no colors or background images: printBackground defaults to false. Set it to true and check your print color CSS.
  • Screen layout is different: PDF uses print media by default. Add await page.emulateMediaType('screen') before page.pdf(), or create explicit print rules.
  • Fonts fall back to a system font: confirm the font URL is reachable from the conversion host and wait for document.fonts.ready. The guide states that PDF generation itself waits for fonts, but inaccessible font files cannot be used.
  • Images or charts are missing: wait for the page’s data-fetching code and image elements, use absolute or embedded resources, and only then generate the PDF.
  • Content is clipped at an edge: review paper dimensions, margins, wide fixed-width elements and long unbreakable strings. Try landscape orientation for wide tables.
  • Your CSS page size is ignored: set preferCSSPageSize: true and avoid simultaneously expecting format to win.
  • Only part of the document is needed: use the documented pageRanges option rather than deleting content from the HTML.
  • The process hangs: inspect navigation and application requests. A page waiting forever for a request will also delay a network-idle readiness strategy; add an explicit timeout policy and a deterministic ready selector in your own application.
  • The browser cannot start in production: verify that the runtime permits launching Chromium and that its required executable and temporary directories are available. This is an environment issue, not a PDF option.

Reliability, performance and operating cost

There is no single conversion time or memory figure that applies to every HTML page. Rendering cost depends on page size, JavaScript, images, fonts and the browser environment. Reuse a controlled browser process for a queue of jobs when your service architecture permits it, but create an isolated page per job and close pages after completion. Limit navigation and asset waits so a failed site cannot occupy a worker indefinitely.

For repeatable output, pin your Puppeteer version, keep a representative HTML fixture, and compare PDFs after upgrades. Test both print and screen media if your product supports both. The Puppeteer options reference and defaults can change between versions, so consult the reference that matches the installed package.

The sources do not establish a universal hosted-service price or a benchmark against other renderers. Your cost calculation should include the browser runtime, compute time, storage and any external assets your deployment uses.

Rank #4
Sale
NDYIN Portable Printers Wireless for Travel, N80 Bluetooth Thermal Printer
  • Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
  • No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
  • Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
  • Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
  • The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art
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 is a website screenshot API and MCP server for developers. A GET request can return a PNG, JPEG, WebP or PDF from a URL, so it is useful when the HTML already lives at a reachable address and you do not want to maintain Chromium infrastructure. See the ScreenshotNeo API documentation for the current output and capture parameters.

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

cURL:

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

Python:

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

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = require('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be turned off. Bot checks and 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. Its MCP server exposes take_screenshot, get_page_info and capture_pdf tools to Claude, Cursor and other MCP clients.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free. Every feature is included on every plan. For PDF capture, point the request at a public page and select PDF output using the documented API option rather than assuming the example’s .webp filename.

Create a free ScreenshotNeo account to try 1,000 screenshots a month without entering a card.

Frequently asked questions

Can I convert HTML that contains private data?

Yes, with a self-hosted Puppeteer process you control the browser and the source, but you still need to review how remote images, fonts and scripts are fetched. Do not load untrusted HTML in a privileged environment without applying your own isolation and network policy.

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

Why does a PDF look different from a browser screenshot?

A PDF is paginated and generated with print CSS by default, while a screenshot represents a viewport. Differences in media queries, paper size, margins, page breaks and color adjustment are expected unless you deliberately align those settings.

Frequently Asked Questions

Can I convert HTML that contains private data?

Yes. A self-hosted Puppeteer process keeps rendering under your control, but review remote asset requests and isolate untrusted HTML according to your security policy.

Why does a PDF look different from a browser screenshot?

PDF generation is paginated and uses print CSS by default; screenshots represent a viewport. Media queries, paper size, margins, page breaks and color adjustment can therefore change the result.

Quick Recap

Bestseller No. 3
HP Smart Tank 5000 Wireless All-in-One Ink Tank Printer, Scanner, Copier with 2 Years of Ink Included, Best-for-Home, Cartridge-Free, Refillable and AI-Enabled. (5D1B6A)
HP Smart Tank 5000 Wireless All-in-One Ink Tank Printer, Scanner, Copier with 2 Years of Ink Included, Best-for-Home, Cartridge-Free, Refillable and AI-Enabled. (5D1B6A)
PREMIUM SUPPORT - Strong technical expertise to solve issues faster; THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.
$194.03

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.