HTML to PDF in Node.js

Render HTML to PDF from Node.js with the built-in fetch. No Puppeteer and no Chromium download.

Last updated

Node.js 18 and later ship fetch, which is all you need to call POST /v1/render. The response body is the PDF, so you write the bytes to a file:

import { writeFile } from "node:fs/promises";

const headers = { "Content-Type": "application/json" };
if (process.env.PDFRENDER_KEY) headers["X-API-Key"] = process.env.PDFRENDER_KEY;

const res = await fetch("https://api.pdfrender.dev/v1/render", {
  method: "POST",
  headers,
  body: JSON.stringify({
    html: "<h1>Hello</h1><p>Rendered from Node.js.</p>",
    filename: "hello.pdf",
  }),
});
if (!res.ok) {
  const problem = await res.json();
  throw new Error(`${res.status} ${problem.code}: ${problem.detail}`);
}
await writeFile("hello.pdf", Buffer.from(await res.arrayBuffer()));

Save it as render.mjs so top-level await works. The key header is sent only when PDFRENDER_KEY is set.

What the renderer does not do

No JavaScript runs in your HTML. Render charts to SVG in Node.js first and put the SVG into the page. External URLs are rejected, so images and fonts go in as data: URIs (how).

Next step

See which CSS works.

FAQ

Can I generate a PDF in Node.js without Puppeteer?
Yes. One fetch call to /v1/render returns the PDF. There is no Chromium to download, update or size for memory.
Does this work in serverless functions?
Yes. The function only makes an HTTPS request, so no browser binary counts against its size or memory limits.