---
title: "Your runtime, on one page"
description: "Every page of the docs' Your runtime section, in order, on one page."
version: "0.9.0"
url: "https://docs.laminapdf.com/one-page/your-runtime/"
---

# Your runtime, on one page

Every page of the docs' Your runtime section, in order, on one page.

## Browser and bundlers

Load @laminapdf/sdk in a web page through Vite or another bundler.

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`:

**TypeScript**

`packages/sdk/examples/quick-start/browser.ts`:

```ts
// 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());
}
```

**Result:** [hello.pdf](/examples/pdf/hello.pdf)

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](/concepts/how-lamina-thinks.md#three-modules-in-javascript).
- **Vite:** exclude the package from dependency pre-bundling (`optimizeDeps.exclude: ["@laminapdf/sdk"]` in `vite.config.ts`), so the `.wasm` files 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](/guides/fonts-and-text.md), or [open and edit](/guides/edit-a-pdf.md) a file.

## Node

Generate a PDF from Node with @laminapdf/sdk.

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`:

**TypeScript**

`packages/sdk/examples/quick-start/node.ts`:

```ts
// 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();
```

**Result:** [hello.pdf](/examples/pdf/hello.pdf)

Save it as `hello.ts` in a project with `@laminapdf/sdk` [installed](/install.md), and run it with Node 24.2 or newer, which runs TypeScript files as they are:

```sh
node hello.ts
```

Node 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](/concepts/how-lamina-thinks.md#you-free-what-you-create) explains why.

Next: draw text with [fonts](/guides/fonts-and-text.md), or [open and edit](/guides/edit-a-pdf.md) a file.

## Deno

Use @laminapdf/sdk in 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`:

**TypeScript**

`packages/sdk/examples/quick-start/deno.ts`:

```ts
// 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();
```

**Result:** [hello.pdf](/examples/pdf/hello.pdf)

Save it as `hello.ts` in a project with `@laminapdf/sdk` [installed](/install.md), and run it:

```sh
deno run --allow-read --allow-write hello.ts
```

Lamina PDF's tests run this app in Deno and check that it builds the reference PDF byte for byte.

Next: draw text with [fonts](/guides/fonts-and-text.md), or [open and edit](/guides/edit-a-pdf.md) a file.

## Bun

Use @laminapdf/sdk in 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`:

**TypeScript**

`packages/sdk/examples/quick-start/bun.ts`:

```ts
// 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();
```

**Result:** [hello.pdf](/examples/pdf/hello.pdf)

Save it as `hello.ts` in a project with `@laminapdf/sdk` [installed](/install.md), and run it:

```sh
bun hello.ts
```

Lamina PDF's tests run this app in Bun and check that it builds the reference PDF byte for byte.

Next: draw text with [fonts](/guides/fonts-and-text.md), or [open and edit](/guides/edit-a-pdf.md) a file.

## Cloudflare Workers

Generate PDFs per request in a Cloudflare Worker.

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.Module`s. `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:

`packages/sdk/examples/worker/src/index.ts`:

```ts
// 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:

`packages/sdk/examples/worker/wrangler.toml`:

```toml
# 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 = true
```

TypeScript learns what a font import is from a declaration file next to the code:

`packages/sdk/examples/worker/src/data.d.ts`:

```ts
// 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](https://fonts.google.com/noto/specimen/Noto+Sans) at `src/fonts/NotoSans-Regular.ttf`, and run `npx wrangler dev`.

- **Errors the caller caused** become a `400` with the error's JSON: a name the font can't draw (`missing-glyph`, `encoding-full`). Anything else, such as a broken font file, stays a `500`. See [Errors and warnings](/concepts/errors-and-warnings.md).
- **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](/recipes/cloudflare-worker.md) says what to change in it, and [Troubleshooting](/troubleshooting/javascript.md#init-fails-in-a-cloudflare-worker) covers a Cloudflare Worker that can't load the WebAssembly.

## Rust

Generate a PDF with the Lamina PDF crate.

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](/install.md#rust-laminapdf) explains the version. This is the `hello` example, which is tested on every change:

**Rust**

`crates/laminapdf/examples/hello.rs`:

````rust
//! 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)
}
````

**Result:** [hello.pdf](/examples/pdf/hello.pdf)

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:** `build` takes `BuildOptions`: 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](/concepts/how-lamina-thinks.md#same-input-same-bytes).
- **Stopping a save:** `save` runs to the end. To let another thread stop it, pass a `CancelToken` to `save_with`, or call `save_job` for a job that you step through with a work budget.
- The [Rust API reference](/reference/rust.md) documents every public item.
- When Cargo picks the wrong version or a feature is missing, [Troubleshooting Rust](/troubleshooting/rust.md) has the fix.
