Server-side PDF generation

Generate PDF files with DocStudio on a Node server using createPdfService, Playwright and Chromium, or request them from a browser with createPdfClient.

Server-side PDF output uses a real Chromium, so the PDF comes from the same HTML and CSS as the preview.

Requirements

Node 20.19 or later, playwright 1.50 or later, and a Chromium installed with npx playwright install chromium. Chromium is never bundled with DocStudio.

Create the service

pdf-service.ts
import { compile } from 'docstudio/core';
import { createPdfService, launchPlaywright } from 'docstudio/server';

const service = createPdfService({
  launchBrowser: () => launchPlaywright(),
  limits: { concurrency: 2, jobTimeoutMs: 30000 },
});

export async function toPdf(template: unknown, data: unknown): Promise<Uint8Array> {
  const compiled = compile({ template, data });
  if (compiled.tree === undefined) throw new Error(JSON.stringify(compiled.diagnostics));
  const result = await service.render({ rdt: compiled.tree, options: { title: 'Report' } });
  if (!result.ok) throw new Error(result.diagnostics.map((item) => item.message).join('; '));
  return result.pdf;
}

render returns { ok: true, pdf, pages } or { ok: false, status, diagnostics }. Keep one service per process and call service.close() on shutdown.

What the service enforces

  • A restrictive content security policy for the document.
  • Request interception that allows only data: URLs and resolved assets.
  • A per-job timeout, a concurrency limit and a queue limit. The default job time limit is 60 seconds.
  • No files written to disk, and no document data in logs. Logs carry job identifiers, sizes and timings.
  • Remote images are fetched only from public addresses over https.

Fonts and images

Register fonts with createFontRegistry from docstudio/render and pass them as fonts. Provide an assets resolver that maps asset: identifiers to bytes. A font that is not available falls back to a default, and an image that cannot be resolved is left out.

Request a PDF from a browser

Expose the service behind your own authenticated endpoint, then call it with the browser-safe client:

client.ts
import { createPdfClient } from 'docstudio/pdf';

const client = createPdfClient({
  endpoint: '/api/pdf',
  headers: { authorization: `Bearer ${token}` },
  timeoutMs: 30000,
});
const result = await client.render({ rdt: tree, options: { title: 'Report' } });
if (result.ok) console.log(result.pages);

fetch is optional and defaults to the global fetch. The client validates the request, applies a timeout and reads the page count from the response.

Browser or server?

Use browser printing when the user is present and a print dialog is acceptable. Use the server when you need a file, a background job or an email attachment. The comparison article lists the trade-offs.

Last updated 2026-12-03