Puppeteer PDF: HTML to PDF in Node.js with page.pdf()
Every page.pdf() option with its real default, margins, headers and footers with page numbers, CSS page breaks, waiting for fonts and images, a production server that reuses one browser, Docker and AWS Lambda setup, and the errors you'll actually hit. Tested on Puppeteer 25.19 with Chrome 158.
Last updated
Short answer
Launch Chromium with puppeteer.launch(), load the content with page.goto(url) or page.setContent(html), then call page.pdf({ format: 'A4', printBackground: true, margin }). It returns a Uint8Array, or writes a file if you pass path. Set both format and printBackground: Puppeteer defaults to Letter paper with no backgrounds. Page breaks come from CSS; page numbers from footerTemplate.
Puppeteer is Google's Node.js library for driving Chrome, and page.pdf() uses Chromium's own print engine, so the PDF has real, selectable text and supports any CSS Chrome supports. This guide covers everything between "it works on my laptop" and "it runs in production": the options and their defaults, headers and page numbers, page breaks, timing, a server that doesn't leak memory, containers, serverless, and the errors people search for. Every snippet was run against Puppeteer 25.19.0, which drives Chrome 158, in November 2026.
Install Puppeteer for PDF generation
npm install puppeteer
# Puppeteer 25 is ESM-only and needs Node.js 22.12 or newer.
# The install downloads Chrome for Testing and chrome-headless-shell into ~/.cache/puppeteer.
# On slim Linux images, install unzip first (or add the optional yauzl package):
# without it the browser download fails but npm install still exits 0.Two changes in Puppeteer 25 (May 2026) trip up older tutorials. The package is ESM-only, so use import puppeteer from "puppeteer" in a .mjs file or a project with "type": "module". (On Node 22.12 and newer, require("puppeteer") still works through Node's support for requiring ES modules.) And puppeteer.executablePath() and puppeteer.defaultArgs() now return Promises, which matters for serverless setups. If you bring your own Chrome or Chromium, install puppeteer-core instead; it skips the browser download and requires an executablePath.
Puppeteer HTML to PDF: the basic example
This is the whole pipeline for a live page. The try/finally matters more than it looks: without it, any navigation error leaves a Chromium process running.
import puppeteer from "puppeteer";
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.goto("https://example.com/report", { waitUntil: "networkidle0" });
await page.pdf({
path: "report.pdf",
format: "A4", // Puppeteer defaults to Letter
printBackground: true, // Puppeteer defaults to false: no background colors or images
margin: { top: "20mm", right: "15mm", bottom: "20mm", left: "15mm" },
});
} finally {
await browser.close();
}For HTML you generate yourself (invoices, reports, tickets), skip the URL and hand Puppeteer the markup:
import puppeteer from "puppeteer";
import { writeFile } from "node:fs/promises";
const html = `<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Invoice INV-1024</title>
<style>
body { font-family: system-ui, sans-serif; font-size: 11pt; }
.total { background: #f1f5f9; padding: 8px 12px; }
</style>
</head>
<body>
<img src="https://example.com/logo.png" width="120" alt="Acme">
<h1>Invoice INV-1024</h1>
<p class="total">Total due: $4,200.00</p>
</body>
</html>`;
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
// "load" (the default) waits for the images and stylesheets this HTML references
await page.setContent(html, { waitUntil: "load" });
const pdf = await page.pdf({ format: "A4", printBackground: true }); // a Uint8Array
await writeFile("invoice.pdf", pdf);
} finally {
await browser.close();
}Without path, page.pdf() resolves to a Uint8Array, not a Node Buffer. Most Node APIs accept either (writeFile, S3 uploads, fetch bodies), but some frameworks don't. More on that in the errors table.
page.setContent vs page.goto
| page.goto(url) | page.setContent(html) | |
|---|---|---|
| Best for | Pages your app already serves, such as a /invoices/123/print route | Templates rendered in Node (Handlebars, EJS, React's renderToStaticMarkup) |
Relative URLs (/logo.png, styles.css) | Resolve against the page URL | Have nothing to resolve against: use absolute URLs, data URIs or a <base href> tag |
waitUntil values | load, domcontentloaded, networkidle0, networkidle2 | load (default) and domcontentloaded only |
| Cookies and auth | Set cookies or headers before navigating | Not needed for inline HTML; external assets load without your app's session |
| Network round trip | Yes, to your own server | No; assets referenced by the HTML still load |
One correction to a lot of existing advice: page.setContent(html, { waitUntil: "networkidle0" }) is gone. Puppeteer removed the networkidle options from setContent() in v24.43.1 (May 2026) because, in the maintainers' words, "these options never worked". In TypeScript it's now a compile error; in plain JavaScript it still resolves, but it was never a real network-idle wait. Use the default load, then page.waitForNetworkIdle() if the HTML fetches anything with JavaScript.
Puppeteer PDF options (page.pdf reference)
| Option | Default | What it does |
|---|---|---|
path | none | Write the PDF to this file as well as returning it. Relative paths resolve from the working directory. |
format | letter | Paper size: Letter, Legal, Tabloid, Ledger, A0 to A6 (case-insensitive). Wins over width and height. |
width / height | none | Custom paper size, as a number (pixels) or a string with a unit, e.g. "80mm" for receipt paper. |
landscape | false | Landscape orientation. |
margin | no margins | { top, right, bottom, left }, each a number (px) or a string in px, in, cm, mm, pt or pc. |
printBackground | false | Print background colors and images. Almost every real document wants true. |
scale | 1 | Rendering scale, between 0.1 and 2. |
preferCSSPageSize | false | Let a CSS @page { size } rule override format, width and height. |
pageRanges | all pages | Pages to print, e.g. "1-5, 8, 11-13". |
displayHeaderFooter | false | Turn on the header and footer templates. |
headerTemplate / footerTemplate | Chromium's default | HTML filled in per page. Elements with the classes date, title, url, pageNumber and totalPages get those values. |
omitBackground | false | Drop the default white background, for PDFs with transparency. |
tagged | true | Experimental: generate a tagged (accessible) PDF. |
outline | false | Experimental: generate a document outline (bookmarks) from headings. |
waitForFonts | true | Wait for document.fonts.ready before printing. |
timeout | 30000 | Milliseconds before giving up; 0 disables it. |
Paper size, scale, and preferCSSPageSize
format beats width/height, and a CSS @page { size: A5 } rule is ignored unless you pass preferCSSPageSize: true. If the document defines its own size, set that flag and drop format; otherwise pick a format and leave @page size out of your CSS. scale shrinks or enlarges the rendering on the page. It's handy for squeezing a wide table onto A4, but fixing the layout's width in print CSS usually looks better.
Print media and colors
page.pdf() renders with the print media type, so @media print rules apply and @media screen rules don't. To print the on-screen design, call await page.emulateMediaType("screen") first; this disables your print styles, so pagination rules inside @media print stop working too. Chromium also adjusts colors for printing by default; -webkit-print-color-adjust: exact (shown in the page-break CSS below) keeps brand colors as designed.
Puppeteer PDF margin
Margins are an object with four optional sides. Numbers are pixels at 96 per inch; strings take px, in, cm, mm, pt or pc. Anything else, such as "2rem", throws Failed to parse parameter value. With no margin at all, Puppeteer prints edge to edge: zero margins, not Chrome's print-dialog defaults.
- Option vs. CSS.
margininpage.pdf()andmarginin a CSS@pagerule both work. Pick one place so you're not debugging two. The headers and footers below need the option, or@pagemargins, to have space to draw in. - The body margin is separate. Browsers add 8px of default
bodymargin on top of the page margin. Setbody { margin: 0 }in print CSS if you want the page margin to be the only one. - Full-bleed backgrounds. For a cover page with color to the edges, use zero page margins and add padding inside your own elements instead.
Headers and footers with page numbers
Turn on displayHeaderFooter and pass HTML templates. Chromium fills elements that have the classes pageNumber, totalPages, date, title (the document's <title>) and url:
const pdf = await page.pdf({
format: "A4",
printBackground: true,
displayHeaderFooter: true,
// Templates don't see the page's CSS: inline every style and set a font size
headerTemplate: `
<div style="font-size:9px; width:100%; padding:0 15mm; color:#64748b;">
<span class="title"></span>
</div>`,
footerTemplate: `
<div style="font-size:9px; width:100%; padding:0 15mm; color:#64748b; text-align:right;">
Page <span class="pageNumber"></span> of <span class="totalPages"></span>
</div>`,
// The header and footer are drawn inside the margins, so leave room for them
margin: { top: "25mm", right: "15mm", bottom: "20mm", left: "15mm" },
});We tested each of these rules against Chrome 158, because they cause most "my footer is missing" questions:
- The page's CSS doesn't reach the templates. Inline every style, and always set
font-size; the default is tiny. - Scripts inside templates don't run. Only the five special classes are filled in.
- External images never load. An
<img src="https://...">in a template isn't even requested. Embed logos asdata:URIs. - Template backgrounds are dropped unless the element has
-webkit-print-color-adjust: exact. - The template spans the full page width, so add horizontal padding to line it up with your content margins.
- Margins must leave room. With zero margins the footer is painted on top of your content.
- A footer alone isn't enough. If you set only
footerTemplate, Chromium prints its default header with the date and title. Pass an empty header:
// Footer only: pass an empty header, or Chromium prints its default date + title header
await page.pdf({
format: "A4",
displayHeaderFooter: true,
headerTemplate: "<span></span>",
footerTemplate: `<div style="font-size:9px; width:100%; text-align:center;">
<span class="pageNumber"></span> / <span class="totalPages"></span></div>`,
margin: { top: "15mm", bottom: "20mm" },
});Alternative: CSS @page margin boxes (Chrome 131+)
Since Chrome 131, Chromium supports CSS page margin boxes, so page numbers can live in your stylesheet instead of in a Puppeteer option. Unlike templates, margin-box content can use the document's fonts. We confirmed counter(page) and counter(pages) render correctly with Puppeteer 25:
/* In the document's own stylesheet (Chrome 131+) */
@page {
size: A4;
margin: 20mm 15mm;
@bottom-right {
content: "Page " counter(page) " of " counter(pages);
font-size: 9pt;
color: #64748b;
}
}
/* Then print with: page.pdf({ preferCSSPageSize: true, printBackground: true }) */Puppeteer PDF page breaks with CSS
Puppeteer has no page-break option. Chromium paginates by the CSS fragmentation rules, and you steer it with break-before, break-after and break-inside. The legacy page-break-* properties are aliases and still work:
/* Start a section on a new page */
.page-break { break-before: page; }
/* Keep these blocks in one piece */
tr, figure, .card { break-inside: avoid; }
/* Don't strand a heading at the bottom of a page */
h2, h3 { break-after: avoid; }
/* thead already repeats on every page in Chromium; keep it a table-header-group */
thead { display: table-header-group; }
tfoot { display: table-footer-group; }
/* At least three lines of a paragraph on each side of a break */
p { orphans: 3; widows: 3; }
/* Print colors exactly as they appear on screen */
* { -webkit-print-color-adjust: exact; print-color-adjust: exact; }- Breaks only apply to block-level boxes, plus flex items, grid items and table rows, per the CSS Fragmentation spec. A
break-before: pageon a<span>does nothing; we checked. - `break-inside: avoid` can't work miracles. If a block is taller than a page, it breaks anyway.
- Long tables are fine. Chromium repeats
<thead>at the top of every page, andtr { break-inside: avoid }keeps rows from splitting. - An extra blank page at the end usually means something is slightly taller than the last page:
height: 100vh, a fixed-height wrapper, or a trailingbreak-after: page. Remove it, or trim the output withpageRanges. - App-shell layouts clip the PDF. A scroll container such as
main { height: 100vh; overflow: auto }, or aposition: fixedwrapper, stops content from flowing onto later pages. In our test, seven pages of text printed as two and as one. Reset them in@media printwithheight: auto; overflow: visible; position: static.
Waiting for fonts, images and JavaScript
Most "blank chart" or "fallback font" PDFs were printed too early. Pick the wait that matches how the content loads:
// 1. A live URL: wait for the network to go quiet (no requests for 500 ms)
await page.goto(url, { waitUntil: "networkidle0" });
// 2. Your own HTML: setContent only accepts "load" and "domcontentloaded" ...
await page.setContent(html, { waitUntil: "load" });
// ... so if the page fetches data with JavaScript, wait for the network separately
await page.waitForNetworkIdle({ idleTime: 500 });
// 3. The most reliable signal: something your page does when it's finished
await page.waitForSelector("#revenue-chart svg");
await page.waitForFunction(() => window.reportReady === true);
// Fonts: page.pdf() already waits for document.fonts.ready (waitForFonts: true)
const pdf = await page.pdf({ format: "A4", printBackground: true });networkidle0 waits until there have been no network connections for 500 ms; networkidle2 allows two. Pages with analytics beacons, chat widgets or long polling may never go fully idle, so networkidle0 can time out after 30 seconds. For your own templates, a selector or a flag your code sets when rendering finishes is the most dependable signal.
Lazy-loaded images need one extra step. In our test, page.pdf() did fetch a native loading="lazy" image at the bottom of a long page, but an IntersectionObserver-based loader never fired, so its image never arrived. If your pages use a JavaScript lazy loader, switch images to eager or scroll once before printing:
// JavaScript lazy loaders (IntersectionObserver) never fire in print. Make them eager,
// or scroll the page once before printing so they load.
await page.evaluate(() => {
for (const img of document.querySelectorAll("img")) img.loading = "eager";
});
await page.evaluate(async () => {
for (let y = 0; y < document.body.scrollHeight; y += window.innerHeight) {
window.scrollTo(0, y);
await new Promise((resolve) => setTimeout(resolve, 100));
}
window.scrollTo(0, 0);
});
await page.waitForNetworkIdle({ idleTime: 500 });Puppeteer PDF generator in Node.js: a production server
Launching Chromium for every request adds a browser start-up to every PDF and makes memory use spiky. A production service keeps one browser, isolates each job, caps concurrency and survives crashes. This Express server does all four. We ran it with 14 simultaneous requests and a deliberately killed browser, and every request returned a PDF:
// server.mjs: npm install express puppeteer
import express from "express";
import puppeteer from "puppeteer";
const MAX_CONCURRENT = 4; // measure with your own documents before raising this
const RECYCLE_AFTER = 500; // start a fresh Chromium after this many PDFs
let browserPromise = null;
let rendered = 0;
function getBrowser() {
browserPromise ??= puppeteer.launch().then((browser) => {
browser.on("disconnected", () => { browserPromise = null; }); // crashed or closed: relaunch next time
return browser;
});
return browserPromise;
}
// A tiny semaphore: at most MAX_CONCURRENT renders at once, the rest wait in line
let active = 0;
const waiting = [];
async function withSlot(task) {
if (active >= MAX_CONCURRENT) await new Promise((resolve) => waiting.push(resolve));
active++;
try {
return await task();
} finally {
active--;
waiting.shift()?.();
}
}
async function htmlToPdf(html) {
const browser = await getBrowser();
const context = await browser.createBrowserContext(); // fresh cookies and storage per job
try {
const page = await context.newPage();
await page.setContent(html, { waitUntil: "load", timeout: 15_000 });
return await page.pdf({
format: "A4",
printBackground: true,
margin: { top: "20mm", right: "15mm", bottom: "20mm", left: "15mm" },
timeout: 15_000,
});
} finally {
await context.close(); // closes the page too, even when setContent or pdf throws
// Recycle Chromium after RECYCLE_AFTER jobs, but only when no other job is using it
if (++rendered >= RECYCLE_AFTER && active === 1) {
rendered = 0;
browserPromise = null;
await browser.close();
}
}
}
const app = express();
app.use(express.json({ limit: "2mb" }));
app.post("/pdf", async (req, res) => {
try {
const pdf = await withSlot(() => htmlToPdf(req.body.html));
// Buffer.from(): Express 4 would JSON-encode a bare Uint8Array
res.type("application/pdf").send(Buffer.from(pdf));
} catch (err) {
console.error(err);
res.status(500).json({ error: "PDF generation failed" });
}
});
const server = app.listen(3000);
process.on("SIGTERM", async () => {
server.close();
await (await browserPromise)?.close();
process.exit(0);
});- One browser, many contexts.
browser.createBrowserContext()gives each job its own cookies and storage, and closing the context closes everything it opened, even on errors. - A concurrency cap. Memory grows with pages in flight. Four is a starting point; measure peak memory for the whole process tree with real documents before raising it.
- Timeouts on every step, so one slow asset can't hold a slot forever.
- Crash recovery and recycling. The
disconnectedhandler relaunches after a crash, and the browser is replaced after 500 jobs, only when it's idle so no in-flight PDF is killed. - Untrusted HTML is a security boundary. HTML from users can load internal URLs from your server's network. Validate input, block requests to private addresses with
page.setRequestInterception(true), or callpage.setJavaScriptEnabled(false)for templates that don't need scripts.
For PDFs that run to hundreds of pages, page.createPDFStream() returns a ReadableStream you can pipe to the response instead of holding the whole file in memory. For where the RAM goes and how to size a pool, see why Puppeteer eats your RAM.
Docker and serverless
Docker
The Puppeteer team publishes an image with Chrome for Testing, its system libraries and fonts for major non-Latin scripts already installed, running as the non-root user pptruser. Pin the tag to your Puppeteer version:
FROM ghcr.io/puppeteer/puppeteer:25.19.0
# The image runs as the non-root user pptruser and already has
# Chrome for Testing, its system libraries and CJK/Thai/Arabic fonts.
COPY --chown=pptruser:pptruser package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --chown=pptruser:pptruser . .
CMD ["node", "server.mjs"]docker build -t pdf-service .
# --init reaps Chromium's child processes; SYS_ADMIN lets Chrome create its sandbox
docker run --init --cap-add=SYS_ADMIN -p 3000:3000 pdf-serviceWithout one of the sandbox options, Chrome in a container exits with No usable sandbox!; as root, it refuses to start without --no-sandbox. The official image has no color emoji font, and Docker gives containers only 64 MB of /dev/shm; Puppeteer already passes --disable-dev-shm-usage by default to cope. All of this, including a slim custom image and safer alternatives to SYS_ADMIN, is in our guide to running headless Chrome in Docker.
AWS Lambda and other serverless platforms
Lambda caps deployment packages at roughly 50 MB, so the full Puppeteer download doesn't fit. The community answer that Puppeteer's own docs point to is @sparticuz/chromium, a compressed Chromium built for serverless, paired with puppeteer-core:
// npm install puppeteer-core @sparticuz/chromium@158
// Match the @sparticuz/chromium major to the Chrome version your Puppeteer supports
// (Puppeteer 25.19.0 targets Chrome 158).
import puppeteer from "puppeteer-core";
import chromium from "@sparticuz/chromium";
export const handler = async (event) => {
const browser = await puppeteer.launch({
args: await puppeteer.defaultArgs({ args: chromium.args, headless: "shell" }),
executablePath: await chromium.executablePath(),
headless: "shell",
});
try {
const page = await browser.newPage();
await page.setContent(event.html, { waitUntil: "load" });
const pdf = await page.pdf({ format: "A4", printBackground: true });
return {
statusCode: 200,
headers: { "content-type": "application/pdf" },
body: Buffer.from(pdf).toString("base64"),
isBase64Encoded: true,
};
} finally {
await browser.close();
}
};Its README recommends at least 512 MB of memory and suggests 1,600 MB or more. The binary ships with only the Open Sans font (Latin, Greek and Cyrillic), so add other fonts through a layer, and mark @sparticuz/chromium as external in esbuild or webpack. Google Cloud Run's default runtime doesn't include Chrome's system libraries either, so it needs a custom Dockerfile like the one above.
Common Puppeteer PDF errors and fixes
| Error or symptom | Cause | Fix |
|---|---|---|
Could not find Chrome (ver. 158.0.8127.88) | The browser download didn't run, or the cache path differs at runtime (Docker, CI, a different user) | Run npx puppeteer browsers install chrome, or set cacheDirectory in .puppeteerrc to a path inside the project |
Extraction failed: no zip archiver is available | Puppeteer 25 unpacks Chrome with system unzip or the optional yauzl package, and slim images have neither | apt-get install unzip before npm ci, or npm install yauzl |
Failed to launch the browser process with libnss3.so or similar | Chrome's shared libraries aren't installed | npx puppeteer browsers install chrome --install-deps as root, or use the official Docker image |
No usable sandbox! | The container or host blocks the user namespaces Chrome's sandbox needs | Run with a seccomp profile that allows them or --cap-add=SYS_ADMIN; --no-sandbox only for trusted content |
Running as root without --no-sandbox is not supported | Chrome refuses to sandbox as root | Run as a non-root user (the official image already does) |
TimeoutError: Navigation timeout of 30000 ms exceeded | networkidle0 never reached, or a slow page | Use load plus waitForSelector, or raise timeout |
| Downloaded PDF is corrupt or is JSON text | Express 4's res.send() JSON-encodes a Uint8Array | res.send(Buffer.from(pdf)). Express 5 sends the bytes correctly |
| No background colors or images | printBackground defaults to false | printBackground: true plus print-color-adjust: exact |
| Footer missing or overlapping text | displayHeaderFooter off, no font-size, or no bottom margin | Turn it on, size the text, and leave margin for it |
| Charts empty or fallback fonts | Printed before scripts or web fonts finished | Wait for a selector or ready flag; keep waitForFonts on |
HTML to PDF without Puppeteer
If you'd rather not run a browser at all, or Puppeteer is more machinery than the job needs, these are the realistic options in Node.js, as of November 2026:
| Option | Engine | Takes HTML and CSS? | Runs JavaScript | Good fit |
|---|---|---|---|---|
| Playwright | Chromium (PDF is Chromium-only) | Yes | Yes | Teams already using Playwright for tests. Same print engine, nearly the same page.pdf(). See Playwright PDF |
| Gotenberg | Chromium and LibreOffice in a Docker container | Yes, over HTTP | Yes | Self-hosting a PDF microservice in any language; also converts Office files |
| pdfkit / pdfmake / jsPDF | Pure JavaScript, no browser | No: you draw text and shapes, or describe the document in JSON | Not applicable | Simple, structured documents where you control every element |
| @react-pdf/renderer | Its own layout engine | No: React components with a CSS-like subset | Not applicable | React teams that want a PDF-specific component tree. See React to PDF |
| html-pdf | PhantomJS | Yes | Old WebKit | Nothing new. Its npm page says to migrate to a newer library like Puppeteer |
| Hosted API (RenderKit and others) | Hosted Chromium | Yes | Yes | Chromium-quality output without running Chromium |
Searches for "html pdf vs puppeteer" usually mean the html-pdf package. It renders through phantomjs-prebuilt, which npm marks as deprecated, and html-pdf's own deprecation notice recommends Puppeteer. The pure-JavaScript libraries are lighter and need no browser, but they don't render your existing HTML templates, so you rebuild the layout in their API.
The managed alternative: RenderKit /v1/pdf
Everything above is the price of running Chromium yourself: images that pull in a browser and its libraries, sandbox flags, fonts, memory limits, crash handling and version upgrades. If PDF generation isn't your product, a hosted API trades that for an HTTPS call. RenderKit is ours, so weigh this section accordingly. The request below is the header-and-footer example from earlier, as one call:
// npm install renderkit-sdk
import { writeFile } from "node:fs/promises";
import { RenderKit } from "renderkit-sdk";
const rk = new RenderKit(process.env.RENDERKIT_API_KEY);
const pdf = await rk.pdf({
html, // or url: "https://example.com/report"
page_format: "A4", // the default here; print_background is already true
margin_top: "25mm",
margin_right: "15mm",
margin_bottom: "20mm",
margin_left: "15mm",
header_html:
'<div style="font-size:9px; width:100%; padding:0 15mm; color:#64748b;">' +
'<span class="title"></span></div>',
footer_html:
'<div style="font-size:9px; width:100%; padding:0 15mm; color:#64748b; text-align:right;">' +
'Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>',
});
console.log(pdf.url, pdf.credits_used); // hosted PDF on cdn.renderkit.tech, 2 credits
// Keep your own copy
const res = await fetch(pdf.url, { headers: { "user-agent": "my-app/1.0" } });
await writeFile("report.pdf", Buffer.from(await res.arrayBuffer()));No SDK needed. With a URL and a ready selector:
curl https://api.renderkit.tech/v1/pdf \
-H "x-api-key: $RENDERKIT_API_KEY" \
-H "content-type: application/json" \
-d '{
"url": "https://example.com/report",
"page_format": "A4",
"margin": "20mm",
"wait_for_selector": "#revenue-chart svg"
}'| Puppeteer | RenderKit /v1/pdf | Note |
|---|---|---|
page.goto(url) / page.setContent(html) | url / html | Send exactly one; html up to 2 MB |
format | page_format | A4 (default), A3, A5, Letter, Legal, Tabloid |
width / height | page_width / page_height | CSS length strings |
margin: { top, ... } | margin, or margin_top and friends | Strings such as "16mm"; default 10mm |
printBackground | print_background | Defaults to true, the opposite of Puppeteer |
displayHeaderFooter + templates | header_html / footer_html | Same Chromium template classes |
scale, landscape, pageRanges, preferCSSPageSize | scale, landscape, page_range, prefer_css_page_size | Same meaning |
waitUntil, waitForSelector() | wait_until, wait_for_selector, delay | wait_until defaults to networkidle |
- What you get: no browser in your image, no sandbox or font setup, failed renders refunded, and identical requests served from cache for 0 credits. A PDF costs 2 credits.
- Trade-offs: your HTML goes to a third party, every PDF is a network round trip, renders run in France (EU), and results are served from public (unguessable) URLs on cdn.renderkit.tech, so copy them to your own storage if that matters. There's no SLA.
- Price: a free trial with 500 credits for 14 days (10 requests a minute, 1 concurrent render, 15-second render timeout), then Hobby at $9/month for 5,000 credits. See pricing.
When to keep Puppeteer: you already run Chromium comfortably, your documents can't leave your network, or you need browser control an API doesn't expose, such as multi-step logins or arbitrary scripting.
Related
Screenshots with the same browser: Puppeteer screenshots. Containers: headless Chrome in Docker. Other languages and tools: Playwright PDF, HTML to PDF in Node.js, HTML to PDF in Python. Recipes: invoices, reports, certificates. Every request field is in the PDF API reference.
Common questions
Install puppeteer, launch a browser, open a page, load your content with page.goto(url) or page.setContent(html), then call page.pdf({ path: 'out.pdf', format: 'A4', printBackground: true }). Close the browser in a finally block. Without path, page.pdf() returns the PDF as a Uint8Array.
Pass margin: { top: '20mm', right: '15mm', bottom: '20mm', left: '15mm' } to page.pdf(). Each side takes a number (pixels) or a string in px, in, cm, mm, pt or pc. With no margin option, Puppeteer prints with zero margins. You can use a CSS @page margin instead, but pick one place.
Set displayHeaderFooter: true and put <span class='pageNumber'></span> and <span class='totalPages'></span> in footerTemplate, with an inline font-size and a bottom margin big enough to hold it. Pass headerTemplate: '<span></span>' or Chromium adds a default date and title header. On Chrome 131+, CSS @page margin boxes with counter(page) also work.
Use CSS: give the element break-before: page (or the legacy page-break-before: always). It must be a block-level element; it has no effect on inline elements like span. Use break-inside: avoid on rows, figures and cards you want kept whole, and break-after: avoid on headings.
printBackground defaults to false, so Chromium skips background colors and images. Pass printBackground: true, and add -webkit-print-color-adjust: exact to elements whose colors must not be adjusted for print. Header and footer templates need that property on their own elements.
Usually the PDF was printed too early, or the assets couldn't load. With setContent, relative URLs have nothing to resolve against, so use absolute URLs or data URIs. Wait with networkidle0 (goto), a selector, or a ready flag. JavaScript lazy loaders need a scroll first. In header and footer templates, external images never load; use data URIs.
Puppeteer itself is Node.js only. In Python, pyppeteer is unmaintained according to its README; use Playwright for Python, whose page.pdf() drives the same Chromium print engine. In .NET, PuppeteerSharp is a port with a PdfAsync method. Or call an HTML-to-PDF API over HTTP from any language.
Playwright is the closest alternative (same Chromium engine). Gotenberg runs Chromium in a Docker container behind an HTTP API. pdfkit, pdfmake and jsPDF build PDFs in pure JavaScript but don't render HTML. @react-pdf/renderer uses React components. A hosted API like RenderKit takes HTML and returns a PDF without running a browser.
Ship your first render in 60 seconds.
500 free credits to start. No card. Cancel by ignoring it.