WebAssembly
The engine as a JavaScript package. It renders wherever WebAssembly runs: in the browser, on your servers, at the edge, inside desktop and mobile apps. Offline, with no service to call.
Install
Download the WebAssembly build from your dashboard: an npm package archive named palatine-renderer-…tgz. Install it from the file. Keep the archive in your repository or publish it
to your private registry, so that your CI installs the same build.
npm install ./palatine-renderer-0.1.0.tgz
# or: bun add ./palatine-renderer-0.1.0.tgz The package is @palatine/renderer: ES modules, TypeScript types, no dependencies. Third-party notices
are in dist/third-party.
| Import | Contains |
|---|---|
@palatine/renderer | createRenderer, render, renderPDF, renderResponse, fetchResources, the error classes |
@palatine/renderer/browser | createWorkerRenderer, saveBlob, readWithProgress |
@palatine/renderer/worker | The Web Worker script that createWorkerRenderer drives |
@palatine/renderer/renderer.wasm | The engine as a separate .wasm file, for Cloudflare Workers and custom loading |
The engine needs WebAssembly exception handling: Chrome and Edge 95+, Firefox 100+, Safari 15.2+, Node.js 17+, Bun and Cloudflare Workers.
Create a renderer
import { createRenderer } from "@palatine/renderer";
import { readFile } from "node:fs/promises";
// Create it once and reuse it: starting the engine is the slow part.
const renderer = await createRenderer({
license: await readFile("palatine-license.txt", "utf8"),
});
const pdf = await renderer.render({ html, format: "pdf", fonts });
const png = await renderer.render({ html, format: "png", fonts, width: 1200 }); | Option | Description |
|---|---|
license | The text of your license file, or the PAL1-… / PAL2-… token alone. When omitted,
the PALATINE_LICENSE environment variable is read where one exists. See supplying the license. |
wasmModule | A compiled WebAssembly.Module, as Cloudflare Workers import .wasm files. |
wasmBinary | The bytes of renderer.wasm, when you serve or cache that file yourself. |
maxMemory | Memory ceiling in bytes, at least 32 MiB. See memory. |
Without wasmModule or wasmBinary, the engine embedded in the package is used: there is no .wasm file to serve or configure. A renderer runs one render at a time; concurrent calls queue in
order. Call renderer.dispose() to release it.
The top-level functions render, renderPDF, renderPNG, renderWebP and renderSVG share one renderer created on first use. They take the license
from PALATINE_LICENSE, so they suit servers and scripts.
Render input
| Field | Type | Description |
|---|---|---|
html | string | Required. The document. |
format | "pdf" | "png" | "webp" | "svg" | Required by render; implied by renderPDF and the others. |
css | string | string[] | Extra stylesheets, applied after the document's own. |
width, height | integer (CSS px) | Layout size, 1 to 32768. Default width 800; the height follows the content unless you paginate. |
fonts | FontSource[] | Font files, as { family, data }. See fonts. |
resources | loader | map | Images, stylesheets and @font-face files. See resources. |
baseURL | string | Resolves relative URLs of resources and links. |
options | object | The rendering options, identical to the API's. |
onWarning, onProgress | function | See output, progress and warnings. |
Fonts
The engine reads no system font, so that a document renders the same everywhere. Pass every font the document
uses. Without any usable font, a render fails with No usable font for document text.
const fonts = [
{ family: "Body", data: await readFile("fonts/Body-Regular.woff2") },
{ family: "Body", data: await readFile("fonts/Body-Bold.woff2") },
{ family: "Body", data: await readFile("fonts/Body-Italic.woff2") },
{ family: "Mono", data: await readFile("fonts/Mono.ttf") },
]; - TrueType, WOFF and WOFF2 files are accepted. PDFs embed the glyphs they use.
- Weight and style come from each file. Give several files the same family to cover regular, bold and italic; a variable font covers its whole range alone.
- The first font also serves as the fallback for families the document names but you did not provide.
- Fonts declared with
@font-facein the CSS are loaded as resources instead. - Load a font once and reuse the bytes across renders.
Resources
Images, linked stylesheets and @font-face files are resources. The engine never touches the network or
the file system on its own: you decide how each URL is answered. data: URLs need nothing.
import { fetchResources } from "@palatine/renderer";
// 1. A loader: called with each URL, resolved against baseURL.
await renderer.render({
html, format: "pdf", fonts,
baseURL: "https://example.com/reports/",
resources: { load: async (url) => loadFromYourStorage(url) },
});
// 2. A map, keyed by the URL as written in the document.
await renderer.render({
html, format: "pdf", fonts,
resources: { "logo.png": logoBytes, "theme.css": themeBytes },
});
// 3. fetch, for http(s) URLs. Never the default: you opt in.
await renderer.render({
html, format: "pdf", fonts,
baseURL: "https://example.com/reports/",
resources: fetchResources(),
}); A resource that cannot be loaded rejects the render with Missing resource: …. Set options.missingResources to "ignore" to render without it. On a server, fetchResources() fetches any URL the document names, private addresses included: for documents you do
not control, write a loader that only allows the hosts you trust.
Runtimes
Node.js and Bun
Create the renderer when the process starts. renderResponse wraps a render in an HTTP Response with its content type, length and file name.
import { createRenderer, renderResponse } from "@palatine/renderer";
import { readFile } from "node:fs/promises";
const renderer = await createRenderer({
license: await readFile("palatine-license.txt", "utf8"),
});
const fonts = [{ family: "Body", data: await readFile("Body.ttf") }];
Bun.serve({
port: 3000,
async fetch(request) {
const { html } = await request.json();
return renderResponse(
{ html, format: "pdf", fonts },
{ filename: "document.pdf", renderer },
);
},
}); Browser
Rendering is synchronous inside the engine. For anything longer than a page or two, run it in a Web Worker, as in
the browser example: the page stays responsive, progress is reported while the
engine works, and terminate() can stop it. For a short document, the main thread is enough:
import { createRenderer } from "@palatine/renderer";
const renderer = await createRenderer({ license: "PAL2-…" });
const font = new Uint8Array(await (await fetch("/fonts/Body.ttf")).arrayBuffer());
const blob = await renderer.renderBlob({
html: "<h1>Hello</h1>",
format: "pdf",
fonts: [{ family: "Body", data: font }],
});
// Yours to preview, download or upload. Nothing is shown automatically.
const url = URL.createObjectURL(blob);
document.querySelector("iframe").src = url; A web page is public, and so is the license you ship with it. Use a domain-bound license there.
Cloudflare Workers
Workers import .wasm files as compiled modules: pass it as wasmModule. Keep the license in
a secret (wrangler secret put PALATINE_LICENSE).
import { createRenderer } from "@palatine/renderer";
import wasm from "@palatine/renderer/renderer.wasm";
import font from "./Body.ttf";
let renderer;
export default {
async fetch(request, env) {
renderer ??= createRenderer({ wasmModule: wasm, license: env.PALATINE_LICENSE });
const { html } = await request.json();
const pdf = await (await renderer).render({
html,
format: "pdf",
fonts: [{ family: "Body", data: new Uint8Array(font) }],
});
return new Response(pdf, { headers: { "content-type": "application/pdf" } });
},
}; The package also contains a copy of the engine embedded in JavaScript, which a Worker does not need. Alias it to a small stub so the bundle stays under the size limit, about 5 MB compressed instead of 11:
{
"name": "pdf",
"main": "worker.js",
"compatibility_date": "2026-11-01",
"rules": [{ "type": "Data", "globs": ["**/*.ttf"], "fallthrough": true }],
"alias": { "./palatine-single.js": "./no-embedded-wasm.js" }
} export default () => { throw new Error("createRenderer needs wasmModule"); }; The Worker needs the Workers Paid plan for its size. Its default CPU limit is 30 seconds, configurable up to 300,
with 128 MB of memory: set maxMemory to 64 MiB to leave room for the request and
the output. See Cloudflare Worker limits.
Desktop and mobile apps
In Electron, Tauri or a mobile web view, the package runs as in a browser: bundle it with the app and it renders offline. Use your standard license there, not a domain-bound one: an app's pages are not served from a web domain. You may ship the engine inside an app you publish, under the conditions of the terms: the engine and the license stay inside the app's package.
Output, progress and warnings
// Bytes: the portable result, in every runtime.
const bytes: Uint8Array = await renderer.render({ html, format: "pdf", fonts });
// A Blob, read once from the engine's memory: for downloads and uploads.
const blob: Blob = await renderer.renderBlob({ html, format: "pdf", fonts });
// A stream: a paginated PDF leaves the engine as it is written.
const stream: ReadableStream<Uint8Array> = renderer.renderStream({
html, format: "pdf", fonts, width: 794, height: 1123,
options: { pagination: true },
});
return new Response(stream, { headers: { "content-type": "application/pdf" } }); Rendering never opens a dialog, a preview or a download by itself. In the browser, saveBlob(blob, name) from @palatine/renderer/browser saves a Blob as a file.
await renderer.render({
html, format: "pdf", fonts, width: 794, height: 1123,
options: { pagination: true },
onProgress: (progress) => {
if (progress.phase === "resources") console.log(progress.loaded, "resources loaded");
if (progress.phase === "pages") console.log(progress.painted, "of", progress.total, "pages");
},
onWarning: (warning) => console.warn(warning.code, warning.message, warning.source),
}); onProgress counts resources as they load, then the pages of a paginated PDF as they are painted. onWarning is called once per warning before the promise settles: a
warning means the render succeeded with a documented fallback.
Memory and untrusted input
maxMemory caps the engine's WebAssembly memory. Long paginated PDFs are rendered in slices to stay
under it; a document that cannot fit fails with a MemoryLimitError and the renderer stays usable.
JavaScript values, such as the input string and the returned bytes, are outside the cap.
import { createRenderer, MemoryLimitError } from "@palatine/renderer";
const renderer = await createRenderer({ license, maxMemory: 64 * 1024 * 1024 });
try {
await renderer.render({ html, format: "pdf", fonts });
} catch (error) {
if (error instanceof MemoryLimitError) {
// The document needs more than 64 MiB. The renderer stays usable.
} else throw error;
}
renderer.memory(); // { size, used, maxMemory } in bytes The engine does not execute the document's JavaScript and loads only the resources you answer. It has no time limit, though: a hostile document can still consume CPU. To render input you do not trust, run the renderer in a worker or a process that you can stop from outside, with a memory ceiling.
Errors
| Thrown | When |
|---|---|
TypeError, RangeError | Invalid input: empty html, unknown format or option, size out of range, pagination without a height. |
Error | A missing resource, no usable font, or a license problem. The message says which. |
MemoryLimitError | The document does not fit under maxMemory. error.code is "memory.limit". |
AccessibilityError | A strict PDF/UA render that cannot conform. error.code starts with "accessibility.". |
PdfXError | A PDF/X render that cannot conform, for instance transparency in PDF/X-1a. error.code starts with "pdfx.". |