Guides / Generate PDFs in Node.js

Frameworks · Updated 2026-12-03

Generate PDFs in Node.js

This guide turns JSON into a finished PDF from Node.js. You send a template id and your data to one endpoint and get a file back. There is no browser to install, so the same code runs on a laptop, a container, AWS Lambda or a Vercel function.

You need Node 18 or later (for the built-in fetch) and a DevilPDF API key. The free plan includes 500 documents a month.

#1. Get an API key

Sign up, open API keys in the dashboard and create a key. It starts with dp_live_. Keep it in an environment variable, never in code you commit or ship to a browser:

export DEVILPDF_API_KEY="dp_live_..."

Every account can use seven starter templates: invoice, quote, receipt, statement, report, packing-slip and certificate. This renders the invoice starter:

render.mjs
const res = await fetch("https://devilpdf.com/v1/render", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.DEVILPDF_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    template: "invoice",
    data: {
      number: "INV-1001",
      issue_date: "2026-12-03",
      due_date: "2027-01-02",
      company: { name: "Northwind Studio", address: "410 Bay Street\nToronto, ON M5H 2Y4" },
      customer: { name: "Acme Robotics Inc.", address: "2200 Mission Street\nSan Francisco, CA 94110" },
      items: [
        { name: "Brand identity system", quantity: 1, unit_price: 4800 },
        { name: "Front-end development", description: "Billed hourly", quantity: 46, unit_price: 135 },
      ],
      tax_rate: 13,
      tax_label: "HST",
    },
    filename: "INV-1001",
  }),
});

const doc = await res.json();
if (!res.ok) throw new Error(`${doc.error.type}: ${doc.error.message}`);
console.log(doc.url, doc.pages);

Run it with node render.mjs. The response is a document object with an id, the page count in pages, and a signed download link in url. The template adds up the line items, tax and total itself, so you never send totals.

To see every field a starter accepts, fetch it and read sample_data:

curl https://devilpdf.com/v1/templates/invoice \
  -H "Authorization: Bearer $DEVILPDF_API_KEY"

#3. Get the PDF bytes instead

Add "output": "file" and the response body is the PDF itself. Nothing is stored on DevilPDF's side.

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

async function renderPdf(body) {
  const res = await fetch("https://devilpdf.com/v1/render", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.DEVILPDF_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ ...body, output: "file" }),
  });
  if (!res.ok) {
    const { error } = await res.json();
    throw new Error(`${error.type}: ${error.message}`);
  }
  return Buffer.from(await res.arrayBuffer());
}

const pdf = await renderPdf({
  template: "receipt",
  data: {
    number: "R-10482",
    paid_at: "2026-12-03",
    company: { name: "Lumen Cycle Works" },
    customer: { name: "Jordan Alvarez" },
    payment: { method: "Visa", last4: "4242" },
    items: [{ name: "Full tune-up", quantity: 1, unit_price: 129 }],
  },
});

await writeFile("receipt.pdf", pdf);
console.log(`Saved receipt.pdf (${pdf.length} bytes)`);

Errors still come back as JSON, so check res.ok before you read the body as a file. The devilpdf-document-id and devilpdf-pages response headers identify the document in your log.

#4. Serve it from Express

A route that streams a PDF to the browser. The API key stays on the server.

server.mjs
import express from "express";

const app = express();

app.get("/invoices/:number.pdf", async (req, res) => {
  const order = await loadOrder(req.params.number);
  if (!order) return res.sendStatus(404);

  const upstream = await fetch("https://devilpdf.com/v1/render", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.DEVILPDF_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      template: "invoice",
      data: order,
      filename: `invoice-${order.number}`,
      output: "file",
    }),
  });

  if (!upstream.ok) {
    const { error } = await upstream.json();
    return res.status(502).json({ error: error.message });
  }

  res.set("Content-Type", "application/pdf");
  res.set("Content-Disposition", `inline; filename="invoice-${order.number}.pdf"`);
  res.send(Buffer.from(await upstream.arrayBuffer()));
});

// Replace with your database lookup.
async function loadOrder(number) {
  return {
    number,
    customer: { name: "Acme Robotics Inc." },
    items: [{ name: "Consulting", quantity: 3, unit_price: 150 }],
  };
}

app.listen(3000);

Without Express, the same thing works in a plain node:http server: call renderPdf() from step 3 and write the buffer with res.writeHead(200, { "Content-Type": "application/pdf" }) and res.end(pdf).

#5. Any language, same code

Add locale and the starter's labels, dates and money switch language. Arabic, Hebrew, Persian and Urdu also flip the page right to left. Fonts for every script are loaded for you.

const pdf = await renderPdf({
  template: "invoice",
  locale: "ar",
  data: {
    number: "INV-1002",
    currency: "SAR",
    customer: { name: "شركة الأفق للتجارة" },
    items: [{ name: "استشارات", quantity: 3, unit_price: 1250 }],
  },
});

See languages and locales for the full list.

#Many documents at once

For hundreds of PDFs, do not loop over /v1/render and wait on each one. Send them to POST /v1/render/batch and get a webhook when they finish. See async and batch.

#Next steps