Node.js PDF Generator: A Production Guide to HTML PDFs
Node.js PDF generator guide covering Puppeteer, wkhtmltopdf, fonts, SSRF, performance, costs, and when a hosted PDF API makes sense.
TL;DR
- PDFGeny renders HTML, URLs, or one of 40 ready document templates through a hosted API; its median render time is 0.6 s.
- A cold headless Chromium process can cost about 7.8 s per request, while a warm browser brings that figure to roughly 0.65 s. Browser lifecycle is often the real Node.js PDF generator problem.
- Puppeteer gives maximum control, but you own Chromium, memory, fonts, browser upgrades, isolation, and operational failures. PDFGeny moves that renderer out of your application.
- PDFGeny's free plan includes 50 documents/month with no card required; overage is $0.009/document, and one batch request can contain up to 100 documents.
A Node.js PDF generator should be judged less by whether it can turn HTML into a PDF and more by what happens after the first successful render. Puppeteer can generate a PDF with page.pdf(), but production systems also have to handle browser startup, web fonts, page breaks, memory pressure, untrusted URLs and deployment upgrades. Puppeteer PDF generation documentation (https://pptr.dev/guides/pdf-generation)
1. Choose the renderer before choosing the API
Chromium is usually the closest match for modern HTML
Chromium is a practical default when the source document already exists as application HTML. CSS layout, JavaScript-driven content, web fonts and print styles are all part of the same browser rendering model. Puppeteer exposes that model directly through Node.js.
The trade-off is operational ownership. A Puppeteer deployment has a browser binary, launch configuration, process lifecycle, memory consumption and security boundary to maintain. A hosted renderer changes that boundary: your application sends document input while the rendering infrastructure owns the browser process.
PDFGeny uses headless Chromium as its default engine, with WeasyPrint as a second rendering engine and Ghostscript for PDF/A-2b output. That gives a Node.js application more than one rendering path without requiring the application to install each engine.
A local library can still be the right answer
Local rendering wins when the workload is only a handful of documents per day and the deployment environment is already predictable. Paying for an API adds a network dependency and a per-document cost that may not buy much at very low volume.
The more interesting threshold is operational rather than numerical. If PDF generation is a tiny feature in a small application, a local library can be easier to reason about than another service. If PDF generation becomes a production subsystem, the browser becomes infrastructure whether the team intended it or not.
| Approach | Control | Operational burden | Good fit |
|---|---|---|---|
| Puppeteer + Chromium | High | High | Custom browser automation and tight renderer control |
| wkhtmltopdf | Legacy HTML-to-PDF control | High | Existing systems that already depend on its rendering behavior |
| Local PDF library | High for document primitives | Usually lower | Simple, low-volume documents and offline generation |
| PDFGeny API | API-level control | Lower browser operations | Applications that need hosted HTML/URL/template rendering |
2. Puppeteer performance is mostly about browser lifecycle
Failure mode: cold Chromium startup
Cold Chromium can cost about 7.8 s per request when a new headless browser is started for every document. Keeping the browser warm brings the observed figure to roughly 0.65 s. That is a fundamentally different architecture from spawning Chrome for each HTTP request.
The common mistake is to benchmark only page.pdf(). A production measurement should include browser launch, page creation, navigation, font loading, PDF generation and cleanup. Otherwise, the number describes the renderer rather than the service.
For a warm Puppeteer process, the basic implementation can look like this:
import puppeteer from "puppeteer";
const browser = await puppeteer.launch();
export async function renderPdf(html) {
const page = await browser.newPage();
try {
await page.setContent(html, { waitUntil: "networkidle0" });
await page.pdf({
format: "A4",
printBackground: true,
preferCSSPageSize: true
});
} finally {
await page.close();
}
}
Puppeteer Page.pdf() uses the print CSS media type, and its current PDF options include controls for margins, paper format, page ranges, background printing and CSS page size.
Failure mode: browser lifecycle leaks
Unbounded pages can become a memory problem even when each individual document is small. Reusing one browser while creating and closing pages per job is a different lifecycle from launching one browser per job, and a queue can prevent concurrent document creation from overwhelming the host.
PDFGeny reports a median render time of 0.6 s for its hosted renderer. That number is useful as an API-level reference, but it should not be treated as a promise for every HTML document: network resources, page complexity, fonts and JavaScript can all change render behavior.
3. The hardest PDF bugs are usually rendering bugs
Failure mode: web fonts silently fall back
Web fonts can change line widths, which changes wrapping, which changes page count. A document that looks correct in the browser can therefore produce a different PDF if rendering finishes before the intended font is available.
Puppeteer now exposes waitForFonts in its PDF options, and its documentation states that Page.pdf() waits for fonts by default. The browser API underneath is document.fonts.ready, which resolves after required font loading and layout work complete.
await page.setContent(html, { waitUntil: "networkidle0" });
await page.evaluate(async () => {
await document.fonts.ready;
});
const pdf = await page.pdf({
format: "A4",
printBackground: true,
waitForFonts: true
});
Failure mode: page breaks split semantic content
CSS page breaks should be designed rather than discovered after deployment. Invoice rows, signatures, certificate blocks and table headers have different pagination requirements, so one generic rule rarely works.
.avoid-break {
break-inside: avoid;
}.page-break {
break-before: page;
}
@page {
size: A4;
margin: 16mm;
}
CSS page size also matters. Puppeteer documents preferCSSPageSize as the option that gives an @page declaration priority over explicit width, height or format settings.
For more background on browser-backed rendering, see the Puppeteer production guide for HTML rendering APIs and the Chrome HTML document-to-PDF production guide.
4. URL-to-PDF turns rendering into a security boundary
Failure mode: SSRF through arbitrary URLs
URL rendering is an SSRF risk until the destination is treated as untrusted input. If an application accepts an arbitrary URL and the renderer can fetch it, the renderer becomes a network client controlled indirectly by the caller.
The fix is not simply checking that the string begins with https://. OWASP recommends validating the scheme, resolving the hostname, checking the resolved IPv4 and IPv6 destinations, blocking private and loopback networks, rejecting cloud metadata destinations and validating redirect chains.
Node.js URL validation should therefore happen before the renderer receives the destination:
import dns from "node:dns/promises";
import net from "node:net";
function isPrivate(ip) {
if (net.isIP(ip) === 4) {
return ip === "127.0.0.1" ||
ip.startsWith("10.") ||
ip.startsWith("192.168.") ||
/^172\.(1[6-9]|2\d|3[0-1])\./.test(ip) ||
ip.startsWith("169.254.");
}
return ip === "::1" ||
ip.startsWith("fc") ||
ip.startsWith("fd") ||
ip.startsWith("fe80:");
}
export async function validatePdfUrl(value) {
const url = new URL(value);
if (!["http:", "https:"].includes(url.protocol)) {
throw new Error("Unsupported URL scheme");
}
const addresses = await dns.lookup(url.hostname, { all: true });
if (addresses.some(({ address }) => isPrivate(address))) {
throw new Error("Private or local destination rejected");
}
return url;
}
This example is a baseline rather than a complete SSRF gateway. DNS rebinding, redirects and connection-time address enforcement remain relevant. OWASP specifically warns that checking DNS separately from the eventual connection can leave a time-of-check/time-of-use gap.
Failure mode: treating PDF generation as trusted I/O
PDF generation becomes more sensitive when users control HTML, URLs, images or CSS. Keep network access constrained, set timeouts, isolate rendering where possible, and avoid allowing arbitrary protocols.
The same concern applies to a hosted API: a URL-to-PDF feature has to defend its own renderer infrastructure. For application teams, that is one of the strongest reasons to distinguish an API that accepts trusted HTML from one that fetches arbitrary URLs.
5. API integration changes the operational equation
Failure mode: coupling HTTP requests to long-running rendering
Synchronous rendering is convenient for an invoice endpoint that needs the PDF immediately. For reports, bulk jobs or documents with unpredictable rendering time, an asynchronous job plus webhook is easier to scale.
PDFGeny supports both sync and async jobs, signed webhooks using HMAC, stored documents and batches of up to 100 documents per call. Its template catalog contains 40 ready document templates, which can be useful when the document structure is stable and only data changes.
One practical Node.js request can be kept deliberately small:
const response = await fetch("https://pdfgeny.com/api/v1/render", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.PDFGENY_API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
html: "<html><body><h1>Invoice #1042</h1></body></html>"
})
});
if (!response.ok) {
throw new Error(`PDF API returned ${response.status}`);
}
const pdf = Buffer.from(await response.arrayBuffer());
The same HTTP endpoint can be called from other backends. That matters in mixed stacks where Node.js handles the web layer but another service owns billing or reporting.
curl -X POST https://pdfgeny.com/api/v1/render \
-H "Authorization: Bearer $PDFGENY_API_KEY" \
-H "Content-Type: application/json" \
--data '{"html":"<h1>Invoice #1042</h1>"}' \
--output invoice.pdf
import requests
r = requests.post(
"https://pdfgeny.com/api/v1/render",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"html": "<h1>Invoice #1042</h1>"},
timeout=30,
)
r.raise_for_status()
with open("invoice.pdf", "wb") as f:
f.write(r.content)
<?php
$ch = curl_init("https://pdfgeny.com/api/v1/render");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer ". getenv("PDFGENY_API_KEY"),
"Content-Type: application/json"
],
CURLOPT_POSTFIELDS => json_encode([
"html" => "<h1>Invoice #1042</h1>"
]),
CURLOPT_RETURNTRANSFER => true
]);
$pdf = curl_exec($ch);
if ($pdf === false) {
throw new RuntimeException(curl_error($ch));
}
file_put_contents("invoice.pdf", $pdf);
curl_close($ch);?>
package main
import (
"bytes"
"io"
"net/http"
"os"
)
func main() {
body:= bytes.NewBufferString(`{"html":"<h1>Invoice #1042</h1>"}`)
req, _:= http.NewRequest("POST", "https://pdfgeny.com/api/v1/render", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("PDFGENY_API_KEY"))
req.Header.Set("Content-Type", "application/json")
res, err:= http.DefaultClient.Do(req)
if err!= nil {
panic(err)
}
defer res.Body.Close()
data, _:= io.ReadAll(res.Body)
os.WriteFile("invoice.pdf", data, 0644)
}
require "net/http"
require "json"
uri = URI("https://pdfgeny.com/api/v1/render")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV["PDFGENY_API_KEY"]}"
req["Content-Type"] = "application/json"
req.body = { html: "<h1>Invoice #1042</h1>" }.to_json
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(req)
end
raise res.body unless res.is_a?(Net::HTTPSuccess)
File.binwrite("invoice.pdf", res.body)
For API-versus-library trade-offs, the related PDF generator API production guide and Python API versus libraries guide cover the same architectural decision from adjacent stacks.
Failure mode: assuming legacy renderers are equivalent to Chromium
wkhtmltopdf is not “dead”; it is unmaintained. Its GitHub organization is archived, and the project repository is read-only.
The real cost is often not the binary itself. It is the CSS the renderer does not understand the way a current browser does. Replacing wkhtmltopdf can therefore become a layout migration rather than a package upgrade.
6. Cost and architecture should match document volume
Failure mode: paying for infrastructure you barely use
Low-volume rendering does not automatically justify an API. PDFGeny's free plan covers 50 documents/month without a card, while paid overage is $0.009 per document. At 150 documents in a month, that means 100 documents beyond the included allowance, or $0.90 in overage at that rate.
That comparison should sit beside the engineering cost of a local renderer. A self-hosted Puppeteer service may have no per-PDF API charge, but the team still owns browser processes, deployment images, fonts, patching, concurrency and failure recovery.
| Requirement | Local Node.js renderer | Hosted API |
|---|---|---|
| Few documents per day | Often the better choice | Usually unnecessary |
| Modern HTML/CSS | Puppeteer provides browser control | Chromium available without browser operations |
| 40 predefined document designs | Build and maintain them | Templates available |
| Bulk generation | Build queue and concurrency controls | Up to 100 documents per batch call |
| PDF/A-2b | Own the conversion pipeline | Ghostscript-backed PDF/A-2b output |
The non-obvious conclusion is that an API is not automatically the cheaper architecture. For a handful of documents a day, local generation can be simpler and cheaper. The hosted API becomes more compelling when the operational boundary around Chromium is the problem, not merely the act of creating a PDF.
What We Got Wrong / What Surprised Us
The biggest surprise is the 7.8 s versus 0.65 s browser lifecycle gap. It is easy to describe PDF rendering as a single operation, but browser startup changes the shape of the problem. A benchmark that measures only PDF serialization can hide the expensive part.
Fonts were another trap. A PDF can be structurally valid while still being visually wrong because a web font was unavailable when layout completed. Modern Puppeteer now exposes font waiting explicitly, which reflects how real the problem is.
URL rendering is also more security-sensitive than HTML rendering. The moment a renderer fetches a caller-selected URL, SSRF becomes part of the PDF architecture. OWASP's guidance makes clear that hostname validation alone is insufficient because DNS resolution, redirects and destination addresses all matter.
Practical Takeaways
- Measure browser startup separately from rendering. Time launch, navigation, font readiness and
page.pdf()independently. Time: 30–60 minutes. Difficulty: Low. Expected outcome: identify whether browser lifecycle is your actual latency problem.
- Keep Chromium warm if using Puppeteer. Reuse the browser and close pages after each job instead of launching Chrome per request. The supplied figures show about 7.8 s cold versus 0.65 s warm. Time: 1–3 hours. Difficulty: Medium.
- Make font readiness explicit. Use
document.fonts.readyor Puppeteer's font-waiting option and test the resulting PDF, not just the browser screenshot. Time: 30–90 minutes. Difficulty: Low.
- Threat-model URL rendering. Validate schemes, resolve destinations, reject private, loopback and metadata addresses, and account for redirects. Time: 2–4 hours. Difficulty: High.
- Choose local generation deliberately. If you create only a handful of documents per day, a local library may be the simpler answer. Time: 30 minutes for the architectural decision. Difficulty: Low.
- Move rendering behind an API when browser operations become infrastructure. PDFGeny provides sync and async jobs, HMAC-signed webhooks, stored documents, batches up to 100 and PDF/A-2b output. Time: 1–4 hours for a basic integration. Difficulty: Medium.
If your Node.js application needs HTML-to-PDF rendering but you do not want Chromium, fonts, browser lifecycle and PDF/A conversion inside your deployment, PDFGeny gives you a hosted endpoint with a 50-document monthly free allowance.
FAQ
What is the best Node.js PDF generator for HTML?
Puppeteer is a strong choice when you need direct Chromium control and can operate the browser yourself. Its Page.pdf() API supports print CSS, paper formats, margins, page ranges and CSS page sizing. A hosted service such as PDFGeny is a better architectural fit when the application should not own Chromium infrastructure.
Is Puppeteer better than a PDF API?
Puppeteer is better when renderer-level control matters. A PDF API is better when browser operations, deployment complexity and renderer maintenance are the larger problem. For only a handful of documents per day, a local library can beat both on simplicity.
How do I stop fonts from changing my generated PDF?
FontFaceSet.ready waits until font loading and layout operations have completed, and current Puppeteer PDF options include waitForFonts. Test the actual PDF because font fallback can change line wrapping and page breaks.
Is a URL-to-PDF endpoint safe?
URL-to-PDF is not safe by default when users can control the destination. SSRF defenses should restrict protocols, resolve and classify destination IP addresses, reject private, loopback and metadata networks, and validate redirects. OWASP recommends these controls because URL validation alone can be bypassed through DNS and redirect behavior.
Bottom line: a Node.js PDF generator is a rendering system, not just a function that writes bytes. Puppeteer is excellent when owning that system is acceptable; a local library is sensible for small, simple workloads; and a hosted renderer is useful when Chromium operations have become an infrastructure concern.