Puppeteer PDF: Production Guide for HTML Rendering APIs
Puppeteer PDF explained with production code, Chromium trade-offs, failures, costs, and when a PDF API beats running browsers yourself.
TL;DR
- Puppeteer PDF uses headless Chromium to convert HTML into PDF, but a cold browser process can cost about 7.8 seconds per request; a warm browser can render in about 0.65 seconds.
- PDFGeny exposes POST https://pdfgeny.com/api/v1/render and returns PDFs using headless Chromium by default, with a median render time of 0.6 seconds.
- Production failures usually come from CSS page breaks, missing web fonts, memory pressure, SSRF risks in URL rendering, and browser lifecycle management.
- A local Puppeteer setup is often the right choice for a handful of PDFs per day; an API becomes attractive when maintaining Chromium, fonts, queues, and workers becomes the engineering problem.
- PDFGeny provides 50 free documents per month with no card required, then charges $0.009 per document for overage. Get a free API key to send HTML, a URL or a template and receive a PDF from one API call.
What is Puppeteer PDF, and when should developers use it?
Puppeteer PDF is the PDF generation feature of Puppeteer, the Node.js browser automation library that controls Chromium. The short answer: Puppeteer PDF is a good choice when your application already runs JavaScript rendering logic and you need browser-level HTML/CSS compatibility.
Puppeteer PDF generates output by opening a Chromium page, loading content, waiting for assets, and calling the browser's PDF renderer. A minimal implementation can be only a few lines, but production systems must handle browser startup, fonts, authentication, failures, and resource limits.
const puppeteer = require("puppeteer");
async function createPdf() {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(`
<html>
<body>
<h1>Invoice #1001</h1>
<p>Generated with Puppeteer PDF</p>
</body>
</html>
`);
await page.pdf({
path: "invoice.pdf",
format: "A4",
printBackground: true
});
await browser.close();
}
createPdf();
The first production variable is browser lifetime. A cold headless Chromium process costs about 7.8 seconds per request, while keeping Chromium warm reduces that render path to about 0.65 seconds. The difference is not caused by PDF formatting; it comes from launching and initializing the browser.
PDFGeny uses headless Chromium as its default rendering engine and reports a median render time of 0.6 seconds for its hosted rendering endpoint. The service also supports WeasyPrint for cases where a browser engine is not the preferred option and Ghostscript for PDF/A-2b output.
Puppeteer PDF versus a hosted PDF API
| Approach | Rendering engine | Operational responsibility |
|---|---|---|
| Puppeteer PDF | Local Chromium | Browser processes, containers, fonts, scaling, security |
| PDFGeny API | Headless Chromium, WeasyPrint, Ghostscript PDF/A-2b | HTTP request and application integration |
| WeasyPrint library | Python HTML/CSS renderer | Application runtime and dependencies |
A browser PDF engine solves HTML compatibility. It does not solve production operations around browsers.
Running Puppeteer PDF in production: the failures developers meet
Failure mode: browser memory growth after repeated renders
The failure mode is not "PDF generation is slow"; the failure mode is a browser process accumulating pages, assets, and JavaScript state. A service generating invoices continuously needs page cleanup and browser lifecycle rules.
A common Node.js pattern is keeping one browser alive and creating isolated pages:
const puppeteer = require("puppeteer");
let browser;
async function getBrowser() {
if (!browser) {
browser = await puppeteer.launch({
args: ["--no-sandbox"]
});
}
return browser;
}
async function render(html) {
const browser = await getBrowser();
const page = await browser.newPage();
try {
await page.setContent(html, {
waitUntil: "networkidle0"
});
return await page.pdf({
format: "A4",
printBackground: true
});
} finally {
await page.close();
}
}
The variable that matters here is concurrency. One browser process can handle multiple pages, but every page loads fonts, images, CSS, and JavaScript. The correct limit depends on document complexity, memory limits, and timeout requirements.
Failure mode: web fonts silently falling back
The failure mode is a PDF that looks correct in a browser but uses a different font after export. The cause is often that Chromium finishes rendering before remote fonts complete loading.
The fix is to explicitly wait for fonts:
await page.setContent(html, {
waitUntil: "networkidle0"
});
await page.evaluate(async () => {
await document.fonts.ready;
});
await page.pdf({
format: "A4",
printBackground: true
});
Font handling becomes more visible with invoices, certificates, and multilingual documents. A missing font is not a cosmetic issue when a contract changes line wrapping and moves signatures onto another page.
Failure mode: URL rendering becomes an SSRF vulnerability
The failure mode is accepting any user-provided URL and asking Chromium to fetch it. A URL-to-PDF endpoint can become an SSRF hole if it allows access to internal services, loopback addresses, private networks, or cloud metadata endpoints.
The protection model requires URL validation before the browser receives the request. The host must be resolved, and private, loopback, and metadata addresses must be rejected.
const dns = require("dns").promises;
const net = require("net");
async function isSafeUrl(value) {
const url = new URL(value);
const addresses = await dns.resolve(url.hostname);
return addresses.every((address) => {
return net.isIP(address) &&!address.startsWith("127.") &&
address!== "::1";
});
}
console.log(await isSafeUrl("https://example.com"));
A production implementation needs a full IP range check, not only the examples above. The key point is architectural: a PDF renderer that fetches URLs is also a network client.
When Puppeteer PDF is the wrong tool
The contrarian view: a library can beat an API
The common assumption is that a hosted API is always better than local rendering. That is incorrect for small workloads.
A team producing a few PDFs per day may be better served by a local library. A local renderer avoids network dependency, external billing, and API integration work. The operational cost is near zero when document volume is low and the application already has the required runtime.
The trade-off changes when PDF generation becomes infrastructure. Maintaining Chromium versions, container images, fonts, queues, retries, and security controls becomes part of the product.
| Scenario | Better fit | Reason |
|---|---|---|
| 5 internal PDFs per day | Local library | Simple deployment, no API dependency |
| Customer invoices at application scale | Hosted API or managed workers | Rendering becomes an operational service |
| Browser-specific CSS requirements | Puppeteer PDF | Chromium matches web rendering behavior |
| PDF/A archival output | Engine with PDF/A support | Compliance requirements drive the choice |
PDFGeny supports synchronous and asynchronous jobs, signed HMAC webhooks, stored documents, batch generation of up to 100 documents in one call, and PDF/A-2b output. Those features target systems where PDF creation is part of a workflow rather than a one-off script.
Why wkhtmltopdf is still discussed
The failure mode is assuming older tools are unusable because they are old. wkhtmltopdf is not "dead"; it is unmaintained. The practical problem is that its rendering engine does not keep pace with modern CSS requirements.
The real cost is often not installation. The real cost is redesigning templates around CSS features the renderer does not support.
Developers comparing options should also review related approaches such as wkhtmltopdf alternatives and Chrome HTML document generation costs.
Calling a PDF generation API from real applications
Python example
import requests
response = requests.post(
"https://pdfgeny.com/api/v1/render",
json={
"html": "<h1>Invoice 1001</h1>"
},
headers={
"Authorization": "Bearer YOUR_API_KEY"
}
)
open("invoice.pdf", "wb").write(response.content)
PHP example
<?php
$ch = curl_init("https://pdfgeny.com/api/v1/render");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
"html" => "<h1>Invoice 1001</h1>"
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer YOUR_API_KEY",
"Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$pdf = curl_exec($ch);
file_put_contents("invoice.pdf", $pdf);
Go example
package main
import (
"bytes"
"net/http"
"os"
)
func main() {
body:= bytes.NewBufferString(`{
"html":"<h1>Invoice 1001</h1>"
}`)
req, _:= http.NewRequest(
"POST",
"https://pdfgeny.com/api/v1/render",
body,
)
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")
resp, _:= http.DefaultClient.Do(req)
defer resp.Body.Close()
file, _:= os.Create("invoice.pdf")
defer file.Close()
file.ReadFrom(resp.Body)
}
For teams choosing between a code library and an API, the production decision is usually about ownership. Guides covering Python PDF generator APIs versus libraries and ReportLab PDF generation trade-offs cover the same decision from different runtime perspectives.
What We Got Wrong / What Surprised Us
The biggest surprise is that rendering speed is not mainly a PDF problem. It is a browser lifecycle problem. A cold Chromium startup at about 7.8 seconds changes the architecture decision more than the actual PDF conversion step.
Another unexpected issue is framework interaction. Running sync_playwright inside Django raises SynchronousOnlyOperation unless rendering happens on its own thread. The failure is caused by mixing synchronous browser automation with Django's async execution context.
The practical lesson is that PDF generation is a systems problem. HTML conversion is only one part of the pipeline.
Practical Takeaways
- Measure your document volume first.
Outcome: choose the right architecture. Time estimate: 30 minutes. Difficulty: Easy.
- Fix rendering determinism before scaling.
Wait for fonts, control page breaks, and test complex templates. Time estimate: 2-4 hours. Difficulty: Medium.
- Keep Chromium warm if running Puppeteer yourself.
Outcome: avoid cold-start delays around 7.8 seconds. Time estimate: 1-2 hours. Difficulty: Medium.
- Secure every URL-to-PDF feature.
Outcome: reduce SSRF exposure by validating destinations before rendering. Time estimate: 2-6 hours. Difficulty: Advanced.
- Move to an API when operations become the bottleneck.
Outcome: remove browser worker maintenance from your application stack. Time estimate: one integration session. Difficulty: Medium.
For applications that need invoices, receipts, reports, certificates, contracts, or labels without running Chromium containers, PDFGeny provides one endpoint for HTML, URLs, and templates. The free plan includes 50 documents per month with no card required.
FAQ
Is Puppeteer PDF production-ready?
Puppeteer PDF is production-ready when teams manage browser lifecycle, fonts, security, and resource limits. The main engineering challenge is operating Chromium reliably rather than calling the PDF method.
How fast is Puppeteer PDF?
Performance depends on browser startup strategy and document complexity. A cold headless Chromium process costs about 7.8 seconds per request, while a warm browser path can reach about 0.65 seconds.
Should I use Puppeteer PDF or an API?
Use Puppeteer PDF when you need direct browser control and have low operational overhead. Use a hosted API when PDF rendering needs queues, templates, webhooks, storage, batch processing, or managed infrastructure.
Can Puppeteer PDF create PDF/A files?
Puppeteer PDF alone is focused on browser PDF output. PDF/A requirements usually need a separate conversion or rendering pipeline. PDFGeny supports PDF/A-2b output through its supported engine workflow.