Skip to content
Saimul Islam

safe-html-pdf: Playwright PDF rendering for untrusted or AI-written HTML

Print HTML to PDF with Playwright and headless Chromium, with JavaScript and the network turned off, hard limits, and a layout lint for overflow and broken images.

Install
npm install safe-html-pdf playwright
npx playwright install chromium

Overview

safe-html-pdf is a Playwright PDF renderer for HTML you do not fully trust. It prints HTML to a PDF in headless Chromium with JavaScript turned off and every network request refused. The page can only load the files you hand it through a resolveAsset callback.

While the page is open it also checks the layout, per page or per slide, and reports overflow, text drawn outside the page and images that failed to load, so a bad document is caught before anyone opens it.

html-pdf-node and puppeteer-html-pdf also print HTML to PDF, but they leave JavaScript and the network on and say nothing about the layout. That is fine for HTML you wrote yourself and the wrong default for HTML written by a model or a user. safe-html-pdf renders the quotation PDFs in the Bundlewise CRM.

Examples

Render a slide deck from code
import { writeFile } from 'node:fs/promises';
import { createRenderer } from 'safe-html-pdf';

const renderer = createRenderer({ concurrency: 4 });

const { pdf, pages, warnings } = await renderer.render(html, {
  format: 'slides',
  pageSelector: 'section.slide',
});
await writeFile('deck.pdf', pdf);

for (const warning of warnings) console.warn(warning.message);
await renderer.close();
One-shot render
import { renderPdf } from 'safe-html-pdf';

const { pdf } = await renderPdf('<h1>Invoice</h1>', { format: 'Letter', margin: '15mm' });
Serve only the files you choose
const renderer = createRenderer({
  resolveAsset: (url) => (url.pathname === '/logo.png' ? { body: logoBytes, contentType: 'image/png' } : null),
});
Render from the command line
safe-html-pdf proposal.html -o proposal.pdf --format slides --page-selector section.slide --assets assets
Sample output
Wrote proposal.pdf (3 pages, 15.1 KB)

5 warnings
  page 2  overflow          Page 2 overflows its 1280 x 720 area: div.card
  page 3  broken-image      Page 3: image failed to load: /team.png
  page 3  broken-image      Page 3: image failed to load: https://cdn.example.com/photo.jpg
  -       missing-asset     No file was served for the image request to http://document.invalid/team.png
  -       blocked-request   Blocked image request to https://cdn.example.com/photo.jpg

Features

01JavaScript off
JavaScript is disabled for the whole browser context: inline scripts, event handlers and javascript: URLs do not run, and noscript content is shown.
02Network off
Only the page and the files resolveAsset returns are served. Every other request, whatever its type, scheme or port, is aborted and reported as blocked-request. file:// is never served.
03Layout lint
After fonts and images load, with print styles applied, it reports overflow, text drawn outside the page and broken images, per page or per slide.
04Hard limits
A per-render timeout closes the browser context, at most concurrency renders run at once, and at most queueLimit wait. Beyond that, render() rejects at once with QueueFullError.
05Shared, self-healing browser
One Chromium starts on first use and starts again after it closes or crashes. Every render gets a fresh context, so cookies, cache and storage never carry over.
06Typed errors
Every error the package throws on purpose extends SafeHtmlPdfError and has a code, such as RENDER_TIMEOUT, QUEUE_FULL or BROWSER_NOT_INSTALLED.

CLI usage

Usage
safe-html-pdf <input.html> [-o out.pdf] [options]
-o, --output <file>
PDF to write. Default: the input name with .pdf.
--format <format>
A4 (default), Letter, slides (1280x720) or WIDTHxHEIGHT, for example 1280x720 or 210mmx297mm.
--page-selector <css>
Elements that are the pages of a deck, for example section.slide.
--assets <dir>
Serve the page's images, fonts and styles from this folder.
--strict
Exit 1 when there are any warnings. The PDF is still written.
--json
Print the result as JSON.
--timeout <ms>
Stop a render that takes longer. Default: 30000.

Limits

  • It is not an operating-system sandbox. For untrusted input, run it as an unprivileged user in a container.
  • Time is the only per-render resource limit. There is no cap on HTML size, page count or memory, so put those in front of it if you need them.
  • Pages that need JavaScript to show their content, such as charts and client-side frameworks, print empty.
  • Web fonts from the network are never loaded. Text uses the fonts on the machine plus the ones you serve through resolveAsset.
  • The lint only looks inside img elements. Background images and fonts that fail to load show up only as missing-asset or blocked-request.
  • The queue and the concurrency limit belong to one renderer. Two renderers, or two processes, each have their own.

Frequently asked questions

How do I generate a PDF from HTML in Node with Playwright?

Install safe-html-pdf and playwright, run npx playwright install chromium, then call renderPdf(html) from code or run safe-html-pdf input.html from the command line. You get the PDF bytes, the page count and a list of layout warnings.

Why turn JavaScript off to make a PDF?

HTML written by a model or a user can contain scripts that read local files, call out to the network or change the page after you check it. With JavaScript and the network off, the PDF shows only the markup and the files you chose to serve.

Is it a Puppeteer HTML to PDF alternative?

It does the same job on Playwright. html-pdf-node and puppeteer-html-pdf leave JavaScript and the network on and report nothing about the layout. safe-html-pdf turns both off, limits time and concurrency, and lints each page or slide.

How do I add images and fonts to the PDF?

Serve them through resolveAsset, or point the CLI at a folder with --assets. A path that tries to leave the folder, through .. or a symbolic link, is refused and counts as a missing file. Playwright 1.40 or newer is a peer dependency.

Does it run in Docker?

Yes. In a container, or as root, Chromium may refuse to start with its sandbox on. Pass launch: { chromiumSandbox: false } and isolate the container yourself; the package never turns the sandbox off for you.

  • AI agents

    mcp-guardrails

    AI agent guardrails for MCP servers: dry run and confirm, signed preview tokens, optimistic concurrency, revision undo and errors that teach the agent.

  • Web QA

    viewport-qa

    Responsive design testing that measures the layout at every viewport width: overflow, clipping, inconsistent insets and radii, low-resolution images and layout shift.

  • Web QA

    static-preflight

    A broken link checker and launch checklist for a static site build: SEO basics, links and assets, redirects, share cards, icons, JSON-LD and old-URL coverage.

See all 9 open-source packages

Author

Built by Saimul Islam

Saimul Islam is a Forward Deployed Engineer and Solutions Architect. Several of these packages run in production on DeveloperLook, the Bundlewise CRM and Sitessa.