How to generate a PDF from HTML in Node.js
Published 2 min read
In Node.js, turning HTML into a PDF often means shipping a rendering engine inside your
container and keeping it healthy. With an API it is one HTTP request, and Node already has
fetch. This guide shows a reusable function and how to serve the result from Express and from
a Next.js route, with the rustedf.cloud API.
A function that returns the PDF
const API = 'https://api.rustedf.com/v1/render';
export async function renderPdf(templateId, data, locale = 'en-US') { const response = await fetch(API, { method: 'POST', headers: { Authorization: `Bearer ${process.env.RUSTEDF_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ template_id: templateId, locale, data }), signal: AbortSignal.timeout(40_000), });
if (!response.ok) { const { error } = await response.json().catch(() => ({})); throw new Error(error?.message ?? `Render failed (${response.status})`); } return Buffer.from(await response.arrayBuffer());}fetch is built in from Node.js 18. The successful body is the PDF, so arrayBuffer() gives
you the bytes. On a failure the body is JSON with a stable code and a message.
Keep the key in an environment variable on the server. Set the timeout above the time limit of your plan, so your request does not give up before the service does.
To send HTML instead of a saved template id, use { html: '<h1>{{ name }}</h1>', data }. Pass
anything a user typed through data, not inside the HTML string: values in data are escaped,
and the HTML itself is read as a template.
Retry when the service is busy
A 429 (rate limit) or a 503 (busy) carries a Retry-After header.
export async function renderPdfWithRetry(templateId, data, locale, attempts = 3) { for (let attempt = 1; ; attempt++) { try { return await renderPdf(templateId, data, locale); } catch (error) { if (attempt >= attempts || !error.retryAfter) throw error; await new Promise(resolve => setTimeout(resolve, error.retryAfter * 1000)); } }}For this to work, have renderPdf attach the wait to the error it throws:
if (!response.ok) { const { error } = await response.json().catch(() => ({})); const failure = new Error(error?.message ?? `Render failed (${response.status})`); if ([429, 503].includes(response.status)) { failure.retryAfter = Number(response.headers.get('Retry-After')) || 2; } throw failure;}A failed render costs no credit, so a retry is safe.
From Express
import express from 'express';import { renderPdf } from './render-pdf.js';
const app = express();
app.get('/invoices/:number.pdf', async (req, res) => { try { const pdf = await renderPdf(process.env.INVOICE_TEMPLATE_ID, await buildInvoiceData(req.params.number)); res.type('application/pdf').set('Content-Disposition', `inline; filename="invoice-${req.params.number}.pdf"`).send(pdf); } catch (error) { console.error(error); res.status(502).json({ error: 'The invoice could not be generated.' }); }});From a Next.js route handler
import { renderPdf } from '@/lib/render-pdf';
export async function GET(request: Request) { const number = new URL(request.url).searchParams.get('number') ?? ''; const pdf = await renderPdf(process.env.INVOICE_TEMPLATE_ID!, await buildInvoiceData(number)); return new Response(pdf, { headers: { 'Content-Type': 'application/pdf', 'Content-Disposition': `inline; filename="invoice-${number}.pdf"`, }, });}The key never leaves the server: the browser calls your route, and your route calls the API.
Errors worth handling
| Status | code |
What to do |
|---|---|---|
| 401 | unauthorized |
The key is missing, wrong or revoked. |
| 402 | insufficient_credits |
No credits left. Nothing was rendered. |
| 422 | invalid_template |
The template or its data failed. Read message. |
| 429 | rate_limited |
Wait for Retry-After and retry. |
| 503 | busy |
The service is busy. Wait for Retry-After and retry. |
| 504 | render_timeout |
The document took longer than your plan allows. |
Run POST /v1/validate with the same body while you build the template: it lists anything the
service did not fully support, without returning the PDF or using a credit.
Read Rendering a PDF, Authentication and Errors and limits.
Keep reading
Code and integrations
Generate a PDF in ASP.NET Core: MVC, Razor Pages and minimal APIs
Turn a Razor view into a PDF in ASP.NET Core with one API call: a view renderer, a print-ready view, an MVC action, a Razor Pages handler and the traps to avoid.
3 min read
Code and integrations
Convert a web page to PDF in C# without a headless browser
Fetch a page with HttpClient and turn its HTML into a PDF with one API call in C#. Which pages this suits, which it does not, and how to check before you rely on it.
3 min read
Code and integrations
C# PDF report generator: a paged table with totals and page numbers
Build a PDF report in C# from a list of objects: a table whose header repeats on every page, a total, page numbers and the page count, with one HTTP call.
3 min read
Code and integrations
Save a PDF in C#: to disk, as a download or in blob storage
Save the PDF returned by a render call in C#: write it to disk, send it as a download from ASP.NET Core, keep a signed link or upload it, and avoid saving an error.
2 min read