Skip to content

Developer

Self-Hosted HTML to PDF vs a Hosted API: How to Decide

Should you run headless Chrome for PDFs yourself or call a hosted API? A working Playwright service, what it leaves out, and when each option fits.

Updated 9 min readSublimePDF Team

Getting a first PDF out of headless Chrome takes an afternoon with Puppeteer or Playwright. Running it as a dependable service for months is a different job. You have to deal with browser updates, missing fonts, memory, concurrency, untrusted HTML and timeouts. This guide helps you decide whether that job belongs to your team or to a hosted HTML-to-PDF API.

We start with a small self-hosted service that we actually ran. Then we cover what it leaves out, when self-hosting is the right call, when an API is, and how to move between the two without rewriting your templates.

A minimal self-hosted service

This is about the smallest service we would put behind an internal endpoint. It keeps one Chrome process running, gives each request a fresh browser context, blocks network access for untrusted HTML, limits concurrency and body size, and has a timeout:

// render-service.mjs: a minimal self-hosted HTML-to-PDF service.
// Node 22+, playwright-core, and a Chrome/Chromium install.
import http from "node:http";
import { chromium } from "playwright-core";
 
const PORT = Number(process.env.PORT ?? 3900);
const MAX_CONCURRENT = Number(process.env.MAX_CONCURRENT ?? 2);
const MAX_BODY_BYTES = 2 * 1024 * 1024;
const RENDER_TIMEOUT_MS = 20_000;
 
// One browser process, reused. A fresh context per request isolates cookies and storage.
const browser = await chromium.launch({ channel: "chrome" });
browser.on("disconnected", () => process.exit(1)); // let the supervisor restart us
let active = 0;
 
async function render(html) {
  const context = await browser.newContext({ javaScriptEnabled: false });
  try {
    const page = await context.newPage();
    // Untrusted HTML: block every network request (inline styles, data: images still work).
    await page.route("**/*", (route) => route.abort());
    await page.setContent(html, { waitUntil: "load", timeout: RENDER_TIMEOUT_MS });
    return await page.pdf({ format: "A4", printBackground: true, preferCSSPageSize: true });
  } finally {
    await context.close();
  }
}
 
const withTimeout = (promise, ms) =>
  Promise.race([promise, new Promise((_, reject) => setTimeout(() => reject(new Error("render timeout")), ms))]);
 
http
  .createServer(async (req, res) => {
    if (req.method !== "POST" || req.url !== "/pdf") return res.writeHead(404).end();
    if (active >= MAX_CONCURRENT) return res.writeHead(503, { "Retry-After": "1" }).end("busy");
 
    const chunks = [];
    let size = 0;
    for await (const chunk of req) {
      size += chunk.length;
      if (size > MAX_BODY_BYTES) return res.writeHead(413).end("too large");
      chunks.push(chunk);
    }
 
    active++;
    try {
      const pdf = await withTimeout(render(Buffer.concat(chunks).toString("utf8")), RENDER_TIMEOUT_MS);
      res.writeHead(200, { "Content-Type": "application/pdf", "Content-Length": pdf.length }).end(pdf);
    } catch (error) {
      res.writeHead(500).end(String(error.message));
    } finally {
      active--;
    }
  })
  .listen(PORT, "127.0.0.1", () => console.log(`render service on http://127.0.0.1:${PORT}/pdf`));

Run it with node render-service.mjs, then curl --data-binary @invoice.html -o invoice.pdf http://127.0.0.1:3900/pdf.

What we measured locally

We exercised the service with a small harness (bench.mjs) on one laptop: an Apple M4 Max with 16 cores and 48 GB RAM, running macOS with Node 24.5 and Chrome 158. The input was the sample invoice template filled with its sample data. These numbers describe that machine only. They are not server benchmarks and not SublimePDF figures.

MeasurementResult
Service start, including Chrome launch587 ms
First render after start233 ms
One-page invoice, 20 sequential rendersmedian 112 ms, p90 116 ms
Four-page invoice (60 lines), 10 sequential rendersmedian 151 ms, p90 164 ms
4 parallel clients, 40 requests, limit of 220 rejected with 503; accepted median 160 ms
Untrusted HTML pointing at an internal URL, no blockingChrome made 2 internal requests
Same HTML through the service, with blocking0 internal requests

Two results matter more than the timings. Half the parallel requests were turned away, because a concurrency limit without a queue just moves the problem to your callers. And without request blocking, a customer-supplied <img> and <link> made Chrome call an internal address. Here, that address was a stand-in for a cloud metadata endpoint. That is a server-side request forgery path.

What the minimal service leaves out

The code above is about 50 lines long. Running it in production means taking on the following work.

Browser updates and output drift

You need to keep Chrome patched for security, but Chromium's print output changes between versions. For example, @page margin boxes only work from Chrome 131 onwards, so a template that uses them prints differently on older builds. Pin a browser version, keep a set of regression fixtures (our print CSS fixtures are a starting point), and compare page counts and text before every upgrade.

Fonts

Server images and minimal Linux containers ship with few fonts. Puppeteer's troubleshooting guide installs extra font packages in its Docker example to cover Chinese, Japanese, Arabic, Hebrew and Thai. Without them, those scripts render as empty boxes. Web fonts also introduce a race. In our tests, printing right after DOMContentLoaded embedded the fallback font in 2 of 8 runs. Puppeteer waits for document.fonts.ready by default (waitForFonts), so check what your own library does.

Memory, concurrency and crashes

Each browser context and page costs memory, and a single huge document can use far more than a typical one. You need a concurrency limit, a queue so callers are not simply rejected, a restart policy when Chrome crashes (the example exits on disconnected and relies on a supervisor), and a rule for recycling a browser that has been up for too long.

Sandboxing untrusted HTML

If any part of the HTML comes from users, customers or an AI agent, treat it as untrusted:

  • Block or allowlist network requests, as the example does, so documents cannot reach internal services.
  • Disable JavaScript unless templates need it.
  • Keep Chrome's own sandbox on. Puppeteer's documentation says running without a sandbox is "strongly discouraged" and should only be done when you "absolutely trust the content". Containers often push teams towards --no-sandbox, so plan the container setup to avoid it.
  • Limit request size and render time.

Timeouts that actually stop work

The example's withTimeout returns an error to the caller on time, but it does not stop the page in Chrome. The context closes only when the render finishes. A production version should close the context on timeout and count those events.

Everything around the render

Teams usually also end up building:

  • template storage and versioning, with a preview for non-developers
  • data merging with a template language
  • page numbers and headers (headers and footers guide)
  • PDF post-processing such as merging and compressing
  • retries with idempotency
  • usage metering per customer
  • monitoring

When self-hosting is the right call

  • The documents may not leave your network. Air-gapped systems, strict data residency or contracts that rule out sub-processors make self-hosting the default. Review how SublimePDF handles data before deciding either way.
  • The HTML is fully trusted and produced in-house, and the volume is steady. Most of the sandboxing and queueing work then becomes much smaller.
  • You already run browser infrastructure, for example a Playwright test grid, with the people to maintain it.
  • You need browser flags or engine features a hosted API does not offer.
  • You are prototyping. A local Playwright script is the quickest way to check whether a design prints well.

When a hosted API is the better fit

  • You do not want to own a browser fleet. Browser patching, fonts, sandboxing and capacity become the provider's job. Your job is an HTTP call and error handling.
  • You want to keep sending HTML. The HTML and print CSS you render locally can go to POST /html-to-pdf as they are, optionally with JSON data for placeholders, so moving does not mean rewriting templates.
  • Templates are managed by more people than the developers. If you prefer, save a layout as a template in the SublimePDF app. Your code or agent then sends the template ID and JSON data, and layout changes do not need a deploy.
  • AI agents generate the documents. An agent can call the API through ordinary tool calling, sending HTML or a template ID with structured data. The agent quickstart shows the setup.
  • Volume is uneven or unknown. The fixed plan prices are easier to budget than spare browser capacity. SublimePDF lists Developer at $29/month for 1,000 renders and Business at $99/month for 10,000 renders (see pricing).

Decision checklist

QuestionPoints to self-hostingPoints to a hosted API
Can documents leave your network?NoYes
Who writes the HTML?Only your own codeUsers, customers or agents too
Who maintains browsers, fonts and sandboxing?A team that already doesNobody wants to
Who edits templates?Developers, through deploysDevelopers through deploys (HTML), or non-developers in an app (saved templates)
Volume patternSteady and predictableBursty or unknown
What happens when rendering is down?You page your own on-callYou retry and fall back

To compare costs, count your own figures: engineer hours per month for upgrades and incidents, compute for peak concurrency rather than the average, and the cost of a wrong or missing document. Set them against a plan price. We do not publish a generic number because the inputs differ too much between teams.

A migration path that keeps your options open

Both approaches render HTML and CSS in a browser engine, so the template is the part to keep portable.

  1. Keep templates as plain HTML and print CSS. Use @page, break-inside and a repeating thead rather than library-specific tricks. Keep a copy of every template's source in your own repository.

  2. Separate data from layout. Calculate totals and taxes in your code and pass formatted values. The same JSON then works with a local Handlebars render and with a saved template's template variables.

  3. Put one function in front of rendering, such as renderInvoice(data), so only one place in the code knows which backend is used.

  4. Run both backends side by side. Send the same template and data to each and compare page counts and extracted text, the same checks our fixture scripts make, before you switch traffic. On the hosted side, the request carries the same HTML template, here the sample template.html with data.json, and the API fills the placeholders before rendering:

    jq -n --rawfile html template.html --slurpfile data data.json '{html: $html, data: $data[0]}' \
    | curl -sS -X POST https://api.sublimepdf.com/v1/html-to-pdf \
      -H "Authorization: Bearer $SUBLIMEPDF_API_KEY" \
      -H "Content-Type: application/json" \
      --data-binary @- -o hosted.pdf
  5. Switch gradually, starting with internal documents, and keep the old path available until the fixtures agree.

The HTML templates and JSON data tutorial shows the hosted side of step 4 end to end, including the saved-template option and running generation from your own scheduled jobs. The HTML to PDF API page summarises what the hosted service covers.

Sources

  1. Puppeteer: Troubleshooting (sandbox and fonts in containers) · accessed 23 November 2026
  2. Puppeteer: PDFOptions (waitForFonts, timeout, defaults) · accessed 23 November 2026
  3. Playwright: page.pdf() · accessed 23 November 2026
  4. Chrome for Developers: Add content to the margins of web pages when printed using CSS (Chrome 131) · accessed 23 November 2026

Generate your first PDF with one API call.

Create an account, copy an API key and send HTML, or a template ID with JSON data, from your code or your agent.