Your runtime, on one page
This page shows every Your runtime page in order. Read offline lists every section and the whole guide as one PDF.
Browser and bundlers
In a browser, @laminapdf/sdk finds its .wasm files with new URL("…", import.meta.url). Your bundler emits them as assets next to your code, so they load from your own origin.
This app builds one A4 page that says “Hello, world!” and offers it to your user as hello.pdf:
// Builds a one-page PDF that says "Hello, world!" in the browser and offers it as a download.import { Builder, type BuilderOptions, Font, init } from "@laminapdf/sdk";
/** The space between the page's edge and the text, in points (72 points = 1 inch). */const MARGIN = 72;/** The text's size in points; its baseline sits this far below the margin. */const FONT_SIZE = 24;
/** Offers the PDF to your user as hello.pdf. */function download(pdf: Uint8Array): void { // `slice()` copies the bytes into a plain ArrayBuffer, which is what a Blob accepts. const url = URL.createObjectURL(new Blob([pdf.slice()], { type: "application/pdf" })); const link = document.createElement("a"); link.href = url; link.download = "hello.pdf"; link.click(); // Revoke the URL after the click has been handled; revoking it at once can cancel the download. setTimeout(() => URL.revokeObjectURL(url), 0);}
/** Builds the page and hands its bytes to `save`, which offers a download unless you pass another `save` function. */export async function hello( save: (pdf: Uint8Array) => void | Promise<void> = download, options: BuilderOptions = {},): Promise<void> { await init({ text: true }); using builder = new Builder(options); const page = builder.page("A4"); // Points from the page's top-left corner, y down; the text's baseline sits FONT_SIZE points below the margin. page.surface().text("Hello, world!", { font: Font.standard("Helvetica"), size: FONT_SIZE, at: [MARGIN, MARGIN + FONT_SIZE], }); page.finish(); using doc = builder.finish(); await save(doc.save());}
Import hello from your page’s script and call it when your user asks for the file, for example from a button: button.addEventListener("click", () => hello()). Then start the page with your bundler, such as npx vite.
Lamina PDF’s tests bundle this app with Vite, run it in Chromium, Firefox and WebKit, and check that it builds the reference PDF byte for byte.
- Modules on demand: a page that never draws text never downloads the text module; see three modules in JavaScript.
- Vite: exclude the package from dependency pre-bundling (
optimizeDeps.exclude: ["@laminapdf/sdk"]invite.config.ts), so the.wasmfiles stay next to the JavaScript that loads them. - Content Security Policy: compiling WebAssembly needs
script-src 'wasm-unsafe-eval'. Nothing else is needed.
Next: draw text with fonts, or open and edit a file.
Node
In Node, @laminapdf/sdk reads its .wasm files from the @laminapdf/wasm package as bytes. Call await init({ text: true }) once; after that, every call is synchronous.
This app builds one A4 page that says “Hello, world!” and writes it to hello.pdf:
// Builds a one-page PDF that says "Hello, world!" and writes it to hello.pdf, in Node.import { writeFile } from "node:fs/promises";import { Builder, type BuilderOptions, Font, init } from "@laminapdf/sdk";
/** The space between the page's edge and the text, in points (72 points = 1 inch). */const MARGIN = 72;/** The text's size in points; its baseline sits this far below the margin. */const FONT_SIZE = 24;
/** Builds the page and hands its bytes to `save`, which writes hello.pdf unless you pass another `save` function. */export async function hello( save: (pdf: Uint8Array) => void | Promise<void> = (pdf) => writeFile("hello.pdf", pdf), options: BuilderOptions = {},): Promise<void> { await init({ text: true }); using builder = new Builder(options); const page = builder.page("A4"); // Points from the page's top-left corner, y down; the text's baseline sits FONT_SIZE points below the margin. page.surface().text("Hello, world!", { font: Font.standard("Helvetica"), size: FONT_SIZE, at: [MARGIN, MARGIN + FONT_SIZE], }); page.finish(); using doc = builder.finish(); await save(doc.save());}
// `node hello.ts` runs it (Node 24.2 or newer); imported, it only exports `hello`.if (import.meta.main) await hello();
Save it as hello.ts in a project with @laminapdf/sdk installed, and run it with Node 24.2 or newer, which runs TypeScript files as they are:
node hello.tsNode 22 can’t parse the using that frees the builder and the document, so compile the app with tsc first there. Lamina PDF’s tests run this app in Node 22 (compiled), 24 and 26 and check that it builds the reference PDF byte for byte.
A long-running server should free documents the same way; how Lamina PDF thinks about a PDF explains why.
Next: draw text with fonts, or open and edit a file.
Deno
In Deno, @laminapdf/sdk fetches its .wasm files from next to its own code, through file: URLs. Reading them needs --allow-read, and writing hello.pdf needs --allow-write. Call await init({ text: true }) once; after that, every call is synchronous.
This app builds one A4 page that says “Hello, world!” and writes it to hello.pdf:
// Builds a one-page PDF that says "Hello, world!" and writes it to hello.pdf, in Deno.import { Builder, type BuilderOptions, Font, init } from "@laminapdf/sdk";
/** The space between the page's edge and the text, in points (72 points = 1 inch). */const MARGIN = 72;/** The text's size in points; its baseline sits this far below the margin. */const FONT_SIZE = 24;
/** Builds the page and hands its bytes to `save`, which writes hello.pdf unless you pass another `save` function. */export async function hello( save: (pdf: Uint8Array) => void | Promise<void> = (pdf) => Deno.writeFile("hello.pdf", pdf), options: BuilderOptions = {},): Promise<void> { await init({ text: true }); using builder = new Builder(options); const page = builder.page("A4"); // Points from the page's top-left corner, y down; the text's baseline sits FONT_SIZE points below the margin. page.surface().text("Hello, world!", { font: Font.standard("Helvetica"), size: FONT_SIZE, at: [MARGIN, MARGIN + FONT_SIZE], }); page.finish(); using doc = builder.finish(); await save(doc.save());}
// `deno run --allow-read --allow-write hello.ts` runs it; imported, it only exports `hello`.if (import.meta.main) await hello();
Save it as hello.ts in a project with @laminapdf/sdk installed, and run it:
deno run --allow-read --allow-write hello.tsLamina PDF’s tests run this app in Deno and check that it builds the reference PDF byte for byte.
Next: draw text with fonts, or open and edit a file.
Bun
Bun loads @laminapdf/sdk the way Node does: it reads the .wasm files from the @laminapdf/wasm package. Call await init({ text: true }) once; after that, every call is synchronous.
This app builds one A4 page that says “Hello, world!” and writes it to hello.pdf with Bun.write:
// Builds a one-page PDF that says "Hello, world!" and writes it to hello.pdf, in Bun.import { Builder, type BuilderOptions, Font, init } from "@laminapdf/sdk";
/** The space between the page's edge and the text, in points (72 points = 1 inch). */const MARGIN = 72;/** The text's size in points; its baseline sits this far below the margin. */const FONT_SIZE = 24;
/** Builds the page and hands its bytes to `save`, which writes hello.pdf unless you pass another `save` function. */export async function hello( save: (pdf: Uint8Array) => void | Promise<void> = async (pdf) => { await Bun.write("hello.pdf", pdf); }, options: BuilderOptions = {},): Promise<void> { await init({ text: true }); using builder = new Builder(options); const page = builder.page("A4"); // Points from the page's top-left corner, y down; the text's baseline sits FONT_SIZE points below the margin. page.surface().text("Hello, world!", { font: Font.standard("Helvetica"), size: FONT_SIZE, at: [MARGIN, MARGIN + FONT_SIZE], }); page.finish(); using doc = builder.finish(); await save(doc.save());}
// `bun hello.ts` runs it; imported, it only exports `hello`.if (import.meta.main) await hello();
Save it as hello.ts in a project with @laminapdf/sdk installed, and run it:
bun hello.tsLamina PDF’s tests run this app in Bun and check that it builds the reference PDF byte for byte.
Next: draw text with fonts, or open and edit a file.
Cloudflare Workers
Cloudflare Workers can’t compile WebAssembly at run time. So Wrangler bundles the package’s entry for Cloudflare Workers, which imports both .wasm files as WebAssembly.Modules. init instantiates them once per isolate.
This Cloudflare Worker returns a one-page letter at /?name=… in a standard font, and the same letter at /embedded?name=… in a font bundled with the Cloudflare Worker. Lamina PDF’s tests run it in workerd, Cloudflare’s runtime:
// A Worker that generates a one-page letter per request: at `/?name=` in a standard font, which// needs no font file, and at `/embedded?name=` in a font bundled with the Worker, which the PDF// embeds. A name the font can't draw gets a 400 with the error as JSON. The bundled font is a file// in `src/fonts/` that Wrangler bundles as bytes (wrangler.toml's `rules`); put the fonts your// documents need there.import { Builder, Font, init, isLaminaPdfError, type LaminaPdfError } from "@laminapdf/sdk";import notoSans from "./fonts/NotoSans-Regular.ttf";
/** The longest `?name=` the letter takes. */const MAX_NAME = 100;
/** The letter's font for each path: Helvetica, a standard 14 font, or the bundled Noto Sans. */const FONTS = new Map([ ["/", Font.standard("Helvetica")], ["/embedded", Font.fromBytes(notoSans)],]);
/** A one-page letter to `name` in `font`. */function letter(name: string, font: Font): Uint8Array<ArrayBuffer> { const b = new Builder({ producer: "lamina Worker example" }); try { const page = b.page("A4"); page.surface().text(`Hello, ${name}!`, { font, size: 24, at: [72, 96] }); page.finish(); return saveAndFree(b); } finally { // A no-op after finish(); when drawing threw, it frees the builder's WebAssembly side now // rather than whenever the garbage collector gets to it (an isolate serves many requests). b.free(); }}
/** Finishes `b`, saves the document and frees it (the bytes are a copy in JS memory). */function saveAndFree(b: Builder): Uint8Array<ArrayBuffer> { const doc = b.finish(); try { return doc.save(); } finally { doc.free(); }}
const pdf = (bytes: Uint8Array<ArrayBuffer>): Response => new Response(bytes, { headers: { "content-type": "application/pdf" } });
/** * Whether `e` says the font can't draw the name: the caller's input, not a server fault. Other * errors, such as `invalid-font` for a broken font file, stay a 500. */function isNameError(e: unknown): e is LaminaPdfError { return isLaminaPdfError(e, "missing-glyph") || isLaminaPdfError(e, "encoding-full");}
/** A 400 with the error's ADR 0026 object as JSON. */const badRequest = (body: unknown): Response => Response.json(body, { status: 400 });
// A default export because that is how a Worker module exposes its handlers (the named-exports// rule is for package code).export default { async fetch(request: Request): Promise<Response> { // Loads both modules once per isolate; later requests return at once. await init({ text: true }); const url = new URL(request.url); const font = FONTS.get(url.pathname); if (font === undefined) return new Response("not found", { status: 404 }); const name = url.searchParams.get("name") ?? "world"; if (name.length > MAX_NAME) return badRequest({ message: `name is longer than ${MAX_NAME} characters` }); try { return pdf(letter(name, font)); } catch (e) { // A script the font lacks (`missing-glyph`: Chinese in either font) or, in Helvetica, more // distinct non-WinAnsi Latin letters than its 37 spare codes (`encoding-full`). if (isNameError(e)) return badRequest(e.toJSON()); throw e; } },};Its Wrangler configuration bundles font files as Data modules, so importing a font gives its bytes:
# A Cloudflare Worker that generates a PDF per request with @laminapdf/sdk. Run `npx wrangler dev`# in this folder. Wrangler bundles the package's `workerd` export condition, which imports both# `.wasm` files as `WebAssembly.Module`s (Workers can't compile WebAssembly at run time).name = "lamina-pdf-example"main = "src/index.ts"compatibility_date = "2026-10-01"
# Font files are bundled with the Worker as ArrayBuffers.[[rules]]type = "Data"globs = ["**/*.ttf", "**/*.otf"]fallthrough = trueTypeScript learns what a font import is from a declaration file next to the code:
// Font files import as their bytes: Wrangler bundles them as `Data` modules (wrangler.toml's// `rules`), and this file tells TypeScript what such an import is.declare module "*.ttf" { const data: ArrayBuffer; export default data;}declare module "*.otf" { const data: ArrayBuffer; export default data;}To run it, install @laminapdf/sdk and wrangler in the Cloudflare Worker’s folder (npm install @laminapdf/sdk@0.9.0 wrangler), put a copy of Noto Sans at src/fonts/NotoSans-Regular.ttf, and run npx wrangler dev.
- Errors the caller caused become a
400with the error’s JSON: a name the font can’t draw (missing-glyph,encoding-full). Anything else, such as a broken font file, stays a500. See Errors and warnings. - Memory: the letter frees its builder and document as soon as the bytes are saved, because one isolate serves many requests.
Next: the Cloudflare Worker recipe says what to change in it, and Troubleshooting covers a Cloudflare Worker that can’t load the WebAssembly.
Rust
The laminapdf crate is the one to depend on: it wraps Lamina PDF’s core crates in one API. Add it with cargo add laminapdf@0.9.0, then build a document. Install explains the version. This is the hello example, which is tested on every change:
//! The smallest document: one A4 page with a line of text in a standard 14 font.//!//! ```sh//! cargo run -p laminapdf --example hello -- [out-dir] # writes <out-dir>/hello.pdf (default target/examples-out)//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{BuildOptions, Builder, PageSize, PointPt, Pt, SaveOptions, Standard14};
fn main() -> Result<(), Box<dyn Error>> { let out = PathBuf::from(std::env::args().nth(1).unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; std::fs::write(out.join("hello.pdf"), build(BuildOptions::new())?)?; Ok(())}
/// The document's bytes. `options` can fix the file ID, the producer and the creation date, so/// that the same input gives the same bytes on every run.pub(crate) fn build(options: BuildOptions) -> Result<Vec<u8>, Box<dyn Error>> { let mut b = Builder::new(options); let helvetica = b.standard_font(Standard14::Helvetica)?; let mut page = b.page(PageSize::A4); // Page space: points from the top-left corner, y down; `y` is the text's baseline. page.surface().text( "Hello, world!", &helvetica, Pt::new(24.0), PointPt::from_points(72.0, 96.0), )?; page.finish()?; let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
To run it, save it as src/main.rs in a project that depends on laminapdf, then run cargo run. It writes target/examples-out/hello.pdf, or hello.pdf in the folder you pass: cargo run -- out.
- Same input, same bytes:
buildtakesBuildOptions: fix the file ID, the producer and the creation date in them, and the output never changes; see how Lamina PDF thinks about a PDF. - Stopping a save:
saveruns to the end. To let another thread stop it, pass aCancelTokentosave_with, or callsave_jobfor a job that you step through with a work budget. - The Rust API reference documents every public item.
- When Cargo picks the wrong version or a feature is missing, Troubleshooting Rust has the fix.