> Build an HTML to PDF API in Node.js with Express 5 and Puppeteer: Handlebars templates, streamed PDFs, input limits, tests and a Docker image.

Your app makes invoices and reports in HTML, and your users want them as PDF files. Here you build an HTML to PDF API in Node.js. Its `POST /pdf` endpoint prints HTML, a Handlebars template or a URL with headless Chrome. It streams the PDF back, and it comes with tests and a Docker image.

## The finished HTML to PDF API

Start the service, then send the example invoice request from the repository:

```bash
npm start
```

```bash
curl -X POST http://localhost:3000/pdf \
-H "Content-Type: application/json" \
-d @examples/invoice.json \
-o invoice.pdf
```

The response has status 200, the header `Content-Type: application/pdf` and a one-page A4 PDF of 43 KB. On the test Mac, one render of this invoice (open a page, load, print, close) took about 70 ms. The image shows the top of page 1 of that PDF, converted to PNG with `pdftoppm`:

![Top of page 1 of the invoice PDF from the API, with the seller, the customer, four line items and the total](/assets/en/blog/html-to-pdf-api-nodejs/invoice-pdf-page-1.webp)

| Tested with | Version |
|---|---|
| Node.js | 22.22.3 on the Mac, 22.23.4 in the Docker test |
| Puppeteer | 25.16.0, with Chrome for Testing 156.0.8078.47 |
| Express | 5.3.0 |
| Handlebars | 4.7.10 |
| pdf-lib (tests only) | 1.17.1 |
| Operating systems | macOS 26.7.1 on Apple Silicon (M5) for the tests, Ubuntu 24.04 in GitHub Actions for the Docker image (9 November) |
| Docker base image | `node:22-bookworm-slim` |
| Test date | 9 and 10 November 2026 |

All files are in the [nodejs-puppeteer folder](https://github.com/apisk-com/html-to-pdf/tree/main/nodejs-puppeteer) of the html-to-pdf repository.

## How a request turns into a PDF

To convert HTML to PDF in JavaScript, the service uses Puppeteer. Puppeteer controls Chrome through the Chrome DevTools Protocol (CDP), the protocol of the Chrome developer tools. The service starts one Chrome process and keeps it. Each request gets a new page (a browser tab), and the page closes when the PDF is sent.

Request flow from the client to Chrome and back:

![Sequence diagram: the client posts JSON, the Express app validates it, a Chrome page loads and prints it, the app streams the PDF and closes the page](/assets/en/blog/html-to-pdf-api-nodejs/diagram_client-express-chrome.png)

Each file has one job:

| File | Job |
|---|---|
| `src/server.js` | Starts Chrome, then the HTTP server |
| `src/app.js` | Routes, the body size limit and the error responses |
| `src/validate.js` | Turns the request body into a render job |
| `src/templates.js`, `templates/invoice.hbs` | The invoice template |
| `src/render.js` | Opens a page, loads the content, streams the PDF |
| `test/api.test.js` | Starts the service and tests real PDFs |

## Set up the Node.js project

Create a folder and add `package.json`:

```json
{
"name": "html-to-pdf-api-nodejs",
"version": "1.0.0",
"private": true,
"description": "A small HTML to PDF API with Express 5 and Puppeteer.",
"license": "MIT",
"type": "module",
"engines": {
"node": ">=22.12.0"
},
"scripts": {
"start": "node src/server.js",
"test": "node --test"
},
"dependencies": {
"express": "5.3.0",
"handlebars": "4.7.10",
"puppeteer": "25.16.0"
},
"devDependencies": {
"pdf-lib": "1.17.1"
}
}
```

Then install the packages:

```bash
npm install
```

Notes on this file:

- Exact versions and `package-lock.json` make the build repeatable. A new Puppeteer version brings a new Chrome, which can change the PDF layout.
- Puppeteer 25 needs Node.js 22.12 or later.
- The Puppeteer install script downloads Chrome for Testing into `~/.cache/puppeteer`. On Linux, it needs the `unzip` command to unpack Chrome.
- `pdf-lib` is only for the tests.

## Render HTML to PDF with Puppeteer

Create `src/render.js`. It owns the browser and does the work for each request (the server section explains the two signal options):

```js
import puppeteer from 'puppeteer';

// Limits for one render. Change them with environment variables.
const RENDER_TIMEOUT_MS = Number(process.env.RENDER_TIMEOUT_MS ?? 20_000);
const MAX_OPEN_PAGES = Number(process.env.MAX_OPEN_PAGES ?? 4);
// For a url source: the longest wait for the network to go quiet after the page is parsed.
const NETWORK_IDLE_MS = Number(process.env.NETWORK_IDLE_MS ?? 5_000);

let browserPromise;
let openPages = 0;

// One Chrome process for the whole service. Requests share it.
export function getBrowser() {
browserPromise ??= launchBrowser();
return browserPromise;
}

async function launchBrowser() {
try {
const browser = await puppeteer.launch({
// server.js handles these signals: open requests finish, then Chrome closes.
handleSIGINT: false,
handleSIGTERM: false,
});
// If Chrome crashes, the next request starts a new one.
browser.on('disconnected', () => {
browserPromise = undefined;
});
return browser;
} catch (error) {
browserPromise = undefined;
throw error;
}
}

export async function closeBrowser() {
const browser = await browserPromise;
await browser?.close();
}

// An error that the API returns to the client with status 502 (the target page failed).
function badGateway(message) {
return Object.assign(new Error(message), { status: 502, expose: true });
}

// Opens a url source and fails when Chrome shows an error page or the server answers 4xx or 5xx.
async function openUrl(page, url) {
let response;
try {
response = await page.goto(url, { waitUntil: 'domcontentloaded' });
} catch (error) {
// A network error, for example "net::ERR_CONNECTION_REFUSED". A timeout stays a timeout.
if (error.message.startsWith('net::')) {
throw badGateway(`The target page could not be reached: ${error.message}`);
}
throw error;
}
if (page.url().startsWith('chrome-error://')) {
throw badGateway('The target page could not be reached.');
}
if (response && response.status() >= 400) {
throw badGateway(`The target page answered with status ${response.status()}.`);
}
// Wait for the network to go quiet, but only for a short time. Pages with
// ads or analytics can keep a request open for ever: then print what is there.
await page.waitForNetworkIdle({ idleTime: 500, concurrency: 2, timeout: NETWORK_IDLE_MS }).catch(() => {});
// Cancel requests that are still open. Chrome waits for them before it prints.
await page.evaluate(() => window.stop());
}

// Renders one job to PDF and passes the PDF stream to send().
// The page stays open until send() finishes, then closes in all cases.
export async function renderPdf(job, send) {
if (openPages >= MAX_OPEN_PAGES) {
throw Object.assign(new Error('Too many renders. Try again later.'), {
status: 503,
expose: true,
});
}
openPages++;
let page;
try {
const browser = await getBrowser();
page = await browser.newPage();
page.setDefaultTimeout(RENDER_TIMEOUT_MS);

if (job.url) {
await openUrl(page, job.url);
} else {
// Wait for images and stylesheets that the HTML links to.
await page.setContent(job.html, { waitUntil: 'load' });
}

const pdf = await page.createPDFStream(job.options);
await send(pdf);
} finally {
openPages--;
// close() fails when Chrome crashed. Keep the first error, not this one.
await page?.close().catch(() => {});
}
}
```

One browser serves all requests, because a Chrome launch is slow. On the test Mac, `puppeteer.launch()` took about 400 ms, and a new page took about 20 ms. These are medians of two runs, with other jobs on the machine. A page gives each request its own document and scripts. All pages share one browser profile, so cookies from a `url` source stay for later requests. To keep callers apart, open each page in its own context from `browser.createBrowserContext()`.

The page loads the content in one of two ways:

![Flowchart: the html and template sources use setContent and wait for load, the url source uses goto, checks the status and waits for a quiet network for 5 seconds at most, then both call createPDFStream](/assets/en/blog/html-to-pdf-api-nodejs/diagram_render-source-html.png)

- `page.setContent(html)` is the main path. It waits for `load` by default: the images and stylesheets that the HTML links to. The page address is `about:blank`, so a relative link such as `logo.png` does not load. Use absolute URLs or data URLs. The FAQ at the end shows how to serve the HTML at a base URL, so that relative links work.
- `page.goto(url)` is the second path. With `domcontentloaded`, it returns when Chrome has parsed the HTML. The code then makes sure that the page loaded: a status of 400 or more, or a final address that starts with `chrome-error://`, gives status 502. A 403 block page is not a PDF that you want to keep.
- After that, `page.waitForNetworkIdle()` waits for at most 2 open connections for 500 ms, but only for `NETWORK_IDLE_MS` (5 seconds by default). On a timeout, the render continues. Pages with ads or analytics often keep a connection open for ever, so `networkidle2` can use the whole timeout. Chrome also waits for open requests before it prints, so `window.stop()` cancels them. In a test, a page with an image request that never ended gave a PDF in about 1.3 seconds, with the idle limit at 1 second.

`page.createPDFStream()` returns the PDF as a stream. In Puppeteer 25, `page.pdf()` calls the same function and collects all chunks in memory. Chrome finishes the PDF before the first chunk, so the stream saves memory in Node.js, not time. A print error also occurs before any byte goes out, so the service can still send a JSON error.

The `finally` block closes the page in all cases: success, timeout, bad HTML or a client that disconnects. Without it, each failed request leaves a page open until Chrome runs out of memory. The `.catch()` on `close()` keeps the first error if Chrome crashed.

Two more limits protect the server:

- `setDefaultTimeout()` sets the limit for each step (load, then print), so one request can take two times the limit, plus `NETWORK_IDLE_MS` for a `url` source.
- `MAX_OPEN_PAGES` returns status 503 when a burst of requests arrives. A queue is better for high traffic, but a counter is enough for a first version.

The table compares the Puppeteer defaults with the defaults of this service:

| Option | Puppeteer default | Service default | What it does |
|---|---|---|---|
| `format` | `Letter` | `A4` | Paper size |
| `landscape` | `false` | `false` | Turns the paper |
| `printBackground` | `false` | `true` | Prints background colors and images. Without it, the teal table header of the invoice is white. |
| `margin` | `0` on each side | `15mm` on each side | A CSS `@page { margin: ... }` rule in the HTML wins over this option. |
| `preferCSSPageSize` | `false` | `false` | If `true`, a CSS `@page { size: A5; }` rule wins over `format`. If `false`, Chrome uses `format` and ignores the `A5`. |

The last two rows come from tests with Chrome 156. The [PDFOptions reference](https://pptr.dev/api/puppeteer.pdfoptions) lists the other options, for example `scale`, `pageRanges` and `outline`.

## Validate the request before Chrome sees it

Every request body goes through one function. It returns a render job for Puppeteer or throws an error with status 400. Create `src/validate.js`:

```js
import { templates } from './templates.js';

const FORMATS = ['A3', 'A4', 'A5', 'Letter', 'Legal', 'Tabloid'];
// A number and a unit that Puppeteer understands, for example "15mm" or "0.5in".
const LENGTH = /^\d{1,3}(\.\d{1,2})?(mm|cm|in|px)$/;
const DEFAULT_MARGIN = '15mm';

// An error that the API returns to the client with status 400.
function badRequest(message) {
return Object.assign(new Error(message), { status: 400, expose: true });
}

function isObject(value) {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}

// Turns a request body into a render job: { html } or { url }, plus PDF options.
export function parsePdfRequest(body) {
if (!isObject(body)) {
throw badRequest('Send a JSON object with the header Content-Type: application/json.');
}
const sources = ['html', 'url', 'template'].filter((key) => body[key] !== undefined);
if (sources.length !== 1) {
throw badRequest('Send exactly one of "html", "url" or "template".');
}
const options = parseOptions(body.options ?? {});

if (body.url !== undefined) {
return { url: parseUrl(body.url), options };
}
if (body.template !== undefined) {
return { html: renderTemplate(body.template, body.data ?? {}), options };
}
if (typeof body.html !== 'string' || body.html.trim() === '') {
throw badRequest('"html" must be a string that is not empty.');
}
return { html: body.html, options };
}

function parseUrl(value) {
let url;
try {
url = new URL(value);
} catch {
throw badRequest('"url" must be an absolute URL.');
}
// This blocks file:, data: and other schemes. It is NOT protection against SSRF.
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw badRequest('"url" must start with http:// or https://.');
}
return url.href;
}

function renderTemplate(name, data) {
if (typeof name !== 'string' || !Object.hasOwn(templates, name)) {
throw badRequest(`"template" must be one of: ${Object.keys(templates).join(', ')}.`);
}
if (!isObject(data)) {
throw badRequest('"data" must be a JSON object.');
}
try {
return templates[name](data);
} catch (error) {
throw badRequest(`"data" does not match the template: ${error.message}`);
}
}

// Copy only the options that we allow. Never pass request JSON to page.pdf():
// options such as "path" (write a file on the server) must stay out of reach.
function parseOptions(options) {
if (!isObject(options)) {
throw badRequest('"options" must be a JSON object.');
}
const {
format = 'A4',
landscape = false,
printBackground = true,
preferCSSPageSize = false,
margin = {},
...unknown
} = options;

const unknownNames = Object.keys(unknown);
if (unknownNames.length > 0) {
throw badRequest(`Unknown option "${unknownNames[0]}".`);
}
if (!FORMATS.includes(format)) {
throw badRequest(`"format" must be one of: ${FORMATS.join(', ')}.`);
}
for (const [name, value] of Object.entries({ landscape, printBackground, preferCSSPageSize })) {
if (typeof value !== 'boolean') {
throw badRequest(`"${name}" must be true or false.`);
}
}
return { format, landscape, printBackground, preferCSSPageSize, margin: parseMargin(margin) };
}

function parseMargin(margin) {
if (!isObject(margin)) {
throw badRequest('"margin" must be a JSON object.');
}
const result = {};
for (const side of ['top', 'right', 'bottom', 'left']) {
const value = margin[side] ?? DEFAULT_MARGIN;
if (typeof value !== 'string' || !LENGTH.test(value)) {
throw badRequest(`"margin.${side}" must be a length such as "15mm" or "0.5in".`);
}
result[side] = value;
}
return result;
}
```

The design decisions in this file:

- Exactly one source: a body with both `html` and `url` is an error, not a guess.
- An allowlist for the options. Never pass the request JSON to `page.pdf()`: `path` writes a file on your server, `timeout: 0` turns off the timeout, and `headerTemplate` adds the caller's HTML to every page.
- Strict types: `"landscape": "yes"` gets an error, not a silent `true`.
- Only `http:` and `https:` URLs, so `file:///etc/passwd`, `data:` and `javascript:` URLs fail.

The scheme rule does not stop server-side request forgery (SSRF): a request that makes your server call internal addresses. A caller can send `http://169.254.169.254/`, the cloud metadata address. If your cloud does not require a token there, the metadata comes back in the PDF. The `html` source has the same problem: ` ` loads from your server. A later tutorial in this series shows the protection. Until then, do not expose this service to the internet.

The errors use the same `status` and `expose` fields as the errors of the Express body parser, so one error handler answers both.

## Fill Handlebars templates without HTML injection

Invoices and reports usually use one layout with new data each time. A template on the server is safer than free HTML: the caller cannot change the layout, and Handlebars escapes the values.

Create `src/templates.js`:

```js
import { readFileSync } from 'node:fs';
import Handlebars from 'handlebars';

// A separate Handlebars instance: helpers added here do not leak to other code.
const handlebars = Handlebars.create();

function load(name) {
const file = new URL(`../templates/${name}.hbs`, import.meta.url);
// strict: a missing field stops the render instead of leaving a blank in the PDF.
return handlebars.compile(readFileSync(file, 'utf8'), { strict: true });
}

// The templates are files in this repo. Never compile a template from a request.
export const templates = {
invoice: load('invoice'),
};
```

Create `templates/invoice.hbs`:

```handlebars

Invoice {{number}}

Invoice

No. {{number}} · Issued {{issued}} · Due {{due}}

{{seller.name}}

{{#each seller.address}}{{this}}
{{/each}}

Bill to

{{customer.name}}

{{#each customer.address}}{{this}}
{{/each}}

Description Qty Unit price Amount

{{#each items}}
{{description}} {{quantity}} {{unitPrice}} {{amount}}
{{/each}}
Total due {{total}}

{{note}}

```

Create `examples/invoice.json`, the request body from the first section:

```json
{
"template": "invoice",
"data": {
"number": "2026-0147",
"issued": "9 November 2026",
"due": "23 November 2026",
"seller": {
"name": "Example Studio Ltd",
"address": ["12 Harbour Street", "Bristol BS1 4XE", "United Kingdom"]
},
"customer": {
"name": "Acme Robotics & Co.",
"address": ["400 Market Street", "Portland, OR 97204", "United States"]
},
"items": [
{ "description": "Discovery workshop", "quantity": 1, "unitPrice": "$1,200.00", "amount": "$1,200.00" },
{ "description": "UI design, 12 screens", "quantity": 12, "unitPrice": "$150.00", "amount": "$1,800.00" },
{ "description": "Front-end development (hours)", "quantity": 24, "unitPrice": "$95.00", "amount": "$2,280.00" },
{ "description": "Hosting setup and handover", "quantity": 1, "unitPrice": "$350.00", "amount": "$350.00" }
],
"total": "$5,630.00",
"note": "Pay by bank transfer within 14 days. Quote the invoice number."
},
"options": {
"format": "A4",
"margin": { "top": "18mm", "bottom": "18mm" }
}
}
```

How the escaping works:

- `{{customer.name}}` escapes `&`, ` `, `"`, `'`, the backtick and `=`. `Acme Robotics & Co.` prints correctly, and ` ';
const html = templates.invoice(data);
assert.ok(html.includes(' '));
assert.ok(!html.includes(' '));
});

test('renders a URL', async () => {
const pdf = await readPdf(await postPdf({ url: `${pagesUrl}/` }));
assert.equal(pdf.getPageCount(), 1);
});

test('finishes an open request on SIGTERM, then exits', async () => {
const server = spawn(process.execPath, [fileURLToPath(new URL('../src/server.js', import.meta.url))], {
env: { ...process.env, PORT: '0' },
stdio: ['ignore', 'pipe', 'inherit'],
});
const [line] = await once(server.stdout, 'data');
const url = String(line).match(/http:\/\/\S+/)[0];

const renderStarted = new Promise((resolve) => {
onDelayRequest = resolve;
});
const response = fetch(`${url}/pdf`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: `${pagesUrl}/delay` }),
});
await renderStarted;
server.kill('SIGTERM');

await readPdf(await response);
const [code] = await once(server, 'exit');
assert.equal(code, 0);
});

test('returns 504 when the page does not load in time', async () => {
const res = await postPdf({ url: `${pagesUrl}/slow` });
assert.equal(res.status, 504);
});

test('returns 502 with the target status when the page answers 403', async () => {
const res = await postPdf({ url: `${pagesUrl}/blocked` });
assert.equal(res.status, 502);
assert.match((await res.json()).error, /status 403/);
});

test('returns 502 when Chrome cannot reach the page', async () => {
// Start a server to get a free port, then close it: the port refuses connections.
const closed = createServer().listen(0);
await once(closed, 'listening');
const { port } = closed.address();
closed.close();
const res = await postPdf({ url: `http://127.0.0.1:${port}/` });
assert.equal(res.status, 502);
});

test('prints a page with a request that never finishes, within the time limit', async () => {
const start = Date.now();
const pdf = await readPdf(await postPdf({ url: `${pagesUrl}/hang` }));
assert.equal(pdf.getPageCount(), 1);
assert.ok(Date.now() - start x
', url: 'https://example.com/' }],
['empty HTML', { html: ' ' }],
['a file URL', { url: 'file:///etc/passwd' }],
['a relative URL', { url: '/admin' }],
['an unknown template', { template: 'letter' }],
['template data that does not match', { template: 'invoice', data: { number: '1' } }],
['an unknown format', { html: ' x
', options: { format: 'B5' } }],
['a bad margin', { html: ' x
', options: { margin: { top: '1em' } } }],
['a string for a boolean', { html: ' x
', options: { landscape: 'yes' } }],
['an option that is not allowed', { html: ' x
', options: { path: '/tmp/x.pdf' } }],
['JSON that does not parse', '{"html": '],
];

for (const [name, body] of badRequests) {
test(`returns 400 for ${name}`, async () => {
const res = await postPdf(body);
assert.equal(res.status, 400);
assert.equal(typeof (await res.json()).error, 'string');
});
}

test('returns 400 when the Content-Type is not JSON', async () => {
const res = await fetch(`${baseUrl}/pdf`, { method: 'POST', body: ' Hi
' });
assert.equal(res.status, 400);
});

test('returns 413 for a body over 1 MB', async () => {
const res = await postPdf({ html: 'x'.repeat(1_100_000) });
assert.equal(res.status, 413);
});
```

The tests use real output, not mocks:

- Each PDF starts with `%PDF-`, and pdf-lib counts its pages.
- Page sizes prove the options: A4 is 595 by 842 points, and US Letter with `landscape: true` is 792 by 612. Two `break-before: page` rules give three pages.
- A local HTTP server provides a page for the URL test, a `/slow` page that never answers (504 test), a `/blocked` page with status 403 (502 test) and a `/hang` page with an image request that never ends. A closed port gives the second 502 test.
- The `/hang` test makes sure that the PDF comes within the 3-second limit, so a request that never ends does not block the render.
- One test starts `server.js` as a separate process and sends `SIGTERM` during a render. It expects a complete PDF and the exit code 0.
- The file sets `RENDER_TIMEOUT_MS` to 3 seconds and `NETWORK_IDLE_MS` to 1 second before it imports the app, because `render.js` reads the values when it loads.

Run the tests:

```bash
npm test
```

On the test Mac, the 24 tests took about 13 seconds:

```text
# tests 24
# pass 24
# fail 0
```

## Run the service in Docker

Create `Dockerfile`:

```dockerfile
FROM node:22-bookworm-slim

WORKDIR /app
# Keep Chrome in the image, in a folder that the "node" user can read.
ENV PUPPETEER_CACHE_DIR=/app/.cache/puppeteer
# The service uses Chrome in headless mode, so skip the second browser build.
ENV PUPPETEER_CHROME_HEADLESS_SHELL_SKIP_DOWNLOAD=true

COPY package.json package-lock.json ./
# Puppeteer needs unzip to unpack Chrome. npm ci downloads Chrome.
# --install-deps then adds the Linux libraries that Chrome needs.
RUN apt-get update \
&& apt-get install -y --no-install-recommends unzip fonts-liberation fonts-noto-color-emoji \
&& npm ci --omit=dev \
&& npx puppeteer browsers install chrome --install-deps \
&& rm -rf /var/lib/apt/lists/* /root/.npm

COPY src ./src
COPY templates ./templates

# Do not run Chrome as root.
USER node
ENV NODE_ENV=production PORT=3000
EXPOSE 3000
CMD ["node", "src/server.js"]
```

Create `.dockerignore`, so that the build does not copy your local `node_modules`:

```text
node_modules
out
test
```

Build and start the container:

```bash
docker build -t html-to-pdf-api-nodejs .
```

```bash
docker run --rm --init --cap-add=SYS_ADMIN -p 3000:3000 html-to-pdf-api-nodejs
```

Why each line is there:

- `PUPPETEER_CACHE_DIR` puts Chrome in `/app`, where the `node` user can read it.
- Puppeteer 25 unpacks the Chrome download with `unzip`. Without it, the install script only prints a warning, and Chrome is missing at run time.
- `--install-deps` installs the Linux libraries from the package list that comes with Chrome. It needs root and the apt lists, so it runs before `USER node`.
- `fonts-liberation` has the same letter widths as Arial and Times New Roman, and `fonts-noto-color-emoji` adds emoji. Without fonts, text shows as empty squares.
- `--init` runs a small init process as process 1. It collects the Chrome child processes that end, so they do not stay as zombie processes (ended processes that keep a process table entry).
- `--cap-add=SYS_ADMIN` lets Chrome create the namespaces for its sandbox. The [default seccomp profile of Docker](https://docs.docker.com/engine/security/seccomp/) allows most new namespaces only with `CAP_SYS_ADMIN`. The [Puppeteer Docker guide](https://pptr.dev/guides/docker) uses the same flag.

The other option is the Chrome flag `--no-sandbox`. The [Puppeteer troubleshooting guide](https://pptr.dev/troubleshooting) says to use it only for content that you trust fully. This service renders HTML from other people, so keep the sandbox.

On 9 November, `test.sh` built this image on Ubuntu 24.04 in GitHub Actions, started it with the same flags and sent the example request. It returned a valid PDF of 40,646 bytes. The image is not tested again since the 502 change on 10 November.

> If you do not want to run and update Chrome on your own servers, use the APISK [HTML to PDF API](https://docs.google.com/forms/d/e/1FAIpQLSehVgyeBPWdAuQeVinkCWb0e17QmZ8GpYhARgFHkx2N30rvRA/viewform?usp=pp_url&entry.2061938923=HTML%20to%20PDF%20API%20-%20convert%20url%2C%20html%2C%20markdown%20to%20pdf). It converts a URL, HTML or Markdown to PDF as a hosted service, and it is in early access.

## Puppeteer HTML to PDF errors and fixes

| What you see | Cause | Fix |
|---|---|---|
| `Could not find Chrome (ver. 156.0.8078.47). This can occur if either ...` | The install script did not run, or `PUPPETEER_CACHE_DIR` is different at run time | Run `npx puppeteer browsers install chrome` with the run-time `PUPPETEER_CACHE_DIR` |
| `The browser folder (...) exists but the executable (...) is missing.` | The `unzip` command is missing, so the first install stopped | Install `unzip`, delete the folder in the message, install Chrome again |
| `Failed to launch the browser process` with `error while loading shared libraries: libnss3.so` | Linux libraries for Chrome are missing | Run `npx puppeteer browsers install chrome --install-deps` as root |
| `No usable sandbox!` | The container or the host blocks the namespaces for the Chrome sandbox | Start the container with `--cap-add=SYS_ADMIN`; on an Ubuntu 23.10 or later host, read the AppArmor notes in the Puppeteer troubleshooting guide |
| `Navigating frame was detached` during a shutdown | Puppeteer closed Chrome on `SIGTERM` before the render finished | Launch with `handleSIGTERM: false` and close Chrome after `server.close()` |
| Status 502 with `The target page answered with status 403.` | The site blocks the request or the page does not exist | Open the URL in a browser; the service does not retry a 4xx answer |
| `TimeoutError: Navigation timeout of 20000 ms exceeded` | The page or one of its files did not load in time | Make sure that the URL opens in a browser; remove links to slow servers from the HTML |
| `TimeoutError: Timed out after waiting 20000ms` | Print took too long, often for a very long document | Split the document, or raise `RENDER_TIMEOUT_MS` |
| Status 413 with `{"error":"request entity too large"}` | The body is over the `express.json` limit | Send a template and data, or raise the limit |
| The PDF has no background colors | `printBackground` is `false` | Set `printBackground: true` |
| Images in the HTML are missing | Relative links on an `about:blank` page | Use absolute URLs, data URLs or a base URL (see the FAQ) |
| Letters show as empty squares | The server has no font for that script | Install fonts, for example `fonts-noto-cjk` for Chinese, Japanese and Korean |

## Before you put it in production

The HTML to PDF API works and has tests, but it is not ready for the open internet. Add these parts first:

1. SSRF protection for the `url` and `html` sources: block internal addresses for each request that Chrome makes, also after redirects.
2. Authentication, for example an API key in a header, and a rate limit for each key.
3. A queue in place of the 503 response, if your traffic comes in bursts.
4. Fonts for all languages in your documents.
5. A health endpoint that renders a small PDF, and a restart of Chrome after a fixed number of renders.

Each part extends the same files: `validate.js` for input rules, `render.js` for Chrome and `app.js` for HTTP. The [code is on GitHub](https://github.com/apisk-com/html-to-pdf/tree/main/nodejs-puppeteer), with the tests.

## Frequently Asked Questions

### Why is my Puppeteer PDF blank or missing background colors?

Chrome prints with the print styles, and it leaves out background colors and images unless you set `printBackground: true`. A blank page often means that the content came after the wait ended, for example data that a script loads after the `load` event. Call `page.waitForSelector()` for an element that shows when the data is there, or call `page.waitForNetworkIdle()` with a time limit. Also look for `@media print` rules that hide parts of the page.

### How do I add page numbers to a Puppeteer PDF?

Set `displayHeaderFooter: true` and give a `footerTemplate` that contains `<span class="pageNumber"></span>` and `<span class="totalPages"></span>`. Chrome fills in the numbers on each page. The page styles do not apply to the template, so set a font size in it: in a test with Chrome 156, footer text without a font size was less than 1 point high. Also set a bottom margin, for example `20mm`, and keep the template in `render.js`, not in the request.

### Can I convert HTML to PDF in Node.js without Puppeteer?

Yes. Playwright also controls Chrome, and its `page.pdf()` works only with Chromium. pdfkit and pdfmake build the PDF from JavaScript code and objects, not from HTML and CSS. Gotenberg runs Chromium and LibreOffice in a container with an HTTP API, and WeasyPrint converts HTML to PDF in Python without JavaScript.

### What is the difference between page.pdf() and page.createPDFStream()?

In Puppeteer 25, `page.pdf()` calls `createPDFStream()` and reads all chunks into one `Uint8Array`. With the `path` option, it also writes a file. Use `page.pdf()` when you need all bytes at once, for example for an upload to S3 or a `Content-Length` header. Use the stream to send a large PDF without a second full copy in Node.js memory. Both return only after Chrome finishes the whole document.

### Why do images not load with page.setContent()?

The page has the address `about:blank`, so a relative path such as `img/logo.png` has no base. The simple fixes are absolute URLs, data URLs or a `<base href="https://example.com/assets/">` element in the `head` of the HTML. The better option is to serve the HTML at a base URL through request interception. Relative links then resolve against that URL, and nothing is written to disk:

```js
const baseUrl = 'https://assets.example.com/';
await page.setRequestInterception(true);
page.on('request', (request) => {
 if (request.url() === baseUrl) {
 request.respond({ status: 200, contentType: 'text/html', body: html });
 } else {
 request.continue();
 }
});
await page.goto(baseUrl, { waitUntil: 'load' });
```

In a test with Chrome 156, `img/logo.png` in the HTML loaded from `baseUrl`. Use an address that your own server controls, because Chrome requests the linked files from it.

### What does "Timed out after 30000 ms while waiting for the WS endpoint URL" mean?

`puppeteer.launch()` waits 30 seconds for Chrome to print the address of its DevTools connection. If Chrome starts more slowly or stops during the start, the launch fails with this message. On the test Mac, it occurred when other jobs used all CPU cores. Pass `dumpio: true` to `puppeteer.launch()` to see the Chrome output, and raise the `timeout` launch option only if the server is slow.

---

[View the canonical page](https://apisk.com/blog/html-to-pdf-api-nodejs/) · [Browse llms.txt](https://apisk.com/llms.txt)
