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

# Concepts, on one page

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

## How Lamina PDF thinks about a PDF

Bytes in and out, the same bytes every time, edits kept apart from the opened file, two ways to save, memory you free with `using`, three JavaScript modules.

The rest of the docs build on six ideas. The first two follow from one choice: Lamina PDF treats a PDF as bytes, which you give it and it gives back.

### Bytes in, bytes out

Lamina PDF's core never touches the file system or the network, and it never reads the clock. Your app reads the file, hands Lamina PDF the bytes and stores whatever comes back. The only fetches are the ones you ask for, such as opening a remote file by range requests. That's why the same code runs in a browser, on a server and inside a Cloudflare Worker.

### Same input, same bytes

Because Lamina PDF reads no clock, you pass in dates and file IDs yourself. It then writes the same bytes for the same input, on every run and every platform, so you can test, cache and compare its output byte for byte.

### The file you opened never changes

When you open a document, Lamina PDF keeps its bytes exactly as they were. Every edit goes into an [overlay](/reference/glossary.md#overlay) on top of them. Reading the document reads the overlay first, so you see your edits; undo and redo move through them.

*Edits go into an overlay; saving appends them or writes a new file.*

Opening a PDF gives you a document that holds the file's original bytes, which never change, and an overlay for your edits. `doc.transact`, `undo` and `redo` write only to the overlay, and reading the document reads the overlay first. A save then either appends the edits after the original bytes (`incremental`) or writes every byte of a new file (`fullRewrite`). An incremental save leaves the original bytes untouched, so signatures over them stay valid.

### Two ways to save

A save writes the overlay out in one of two ways:

- **[Incremental save](/reference/glossary.md#incremental-save):** the original bytes, unchanged, followed by a new revision that holds your edits. Signatures over the original stay valid.
- **[Full rewrite](/reference/glossary.md#full-rewrite):** the whole file written again, smaller and tidier, but no longer the original bytes.

The default, `auto`, saves incrementally when it can. A signed file saves only incrementally, and a save fails if your edits break its signatures, unless you pass `invalidateSignatures: true`. [Save a PDF](/guides/save-a-pdf.md) has the details.

This example builds a document, opens its bytes, changes the title and saves incrementally. The saved file starts with the original bytes:

**TypeScript**

`packages/sdk/examples/generate-then-edit.ts`:

```ts
// Generate a document, then open its bytes, edit them and save incrementally. The edit changes
// the metadata in one transaction, and the incremental save keeps the generated bytes as they
// are, with one revision appended.
import { Builder, type BuilderOptions, Document, Font } from "@laminapdf/sdk";

/**
 * The generated file followed by the edit's revision. Needs `init({ text: true })`.
 *
 * @param options - can fix the file ID, the producer and the creation date.
 * @param editedAt - the modification date to record, as a PDF date string.
 */
export function generateThenEdit(options: BuilderOptions = {}, editedAt?: string): Uint8Array<ArrayBuffer> {
  return edit(generate(options), editedAt);
}

/** A one-page draft, saved (a new document is always saved as a full rewrite). */
export function generate(options: BuilderOptions = {}): Uint8Array<ArrayBuffer> {
  using b = new Builder(options);
  const page = b.page("A4");
  page.surface().text("Draft report", { font: Font.standard("Helvetica"), size: 20, at: [72, 96] });
  page.finish();
  b.metadata({ title: "Draft report" });
  using doc = b.finish();
  return doc.save();
}

/** Opens `bytes`, edits the metadata in one transaction (which `undo` could revert) and saves incrementally. */
function edit(bytes: Uint8Array, editedAt?: string): Uint8Array<ArrayBuffer> {
  using doc = Document.open(bytes);
  doc.transact((tx) =>
    tx.setMetadata(
      { title: "Final report", authors: ["Ada Lovelace"] },
      editedAt === undefined ? {} : { at: editedAt },
    ),
  );
  return doc.save({ mode: "incremental" });
}
```

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

### You free what you create

In JavaScript, documents and builders live in WebAssembly memory, whose size the garbage collector can't see. Free each one when you're done. That's why the examples in these docs open documents with `using` instead of `const`.

#### Why the garbage collector isn't enough

A `Document` in JavaScript is a small object that points at a large one: the parsed file inside WebAssembly memory. The garbage collector measures only the small object, so it sees no reason to hurry, and a large document can stay in memory long after your code is done with it. WebAssembly memory also grows but never shrinks. A server that opens one file per request keeps growing until it hits the module's 2 GiB ceiling and throws `out-of-memory`.

#### What `using` does

`using` is a JavaScript declaration, like `const`, that frees its value when the block that declares it ends:

```ts
function pageCount(bytes: Uint8Array): number {
  using doc = Document.open(bytes);
  return doc.pageCount;
} // doc is freed here
```

A block ends when its last line runs, when it returns or when it throws. Each time, JavaScript calls the value's `Symbol.dispose` method, which on a Lamina PDF handle is `free()`. Several `using` declarations in one block are freed in reverse order, last one first.

#### What it saves you

Without `using`, the safe version of the same function needs a `try` block:

```ts
function pageCount(bytes: Uint8Array): number {
  const doc = Document.open(bytes);
  try {
    return doc.pageCount;
  } finally {
    doc.free();
  }
}
```

`using` does the same job in one line, with two gains over the `try` block:

- **Nothing to forget:** the free is part of the declaration, so no document goes without its `try` block. No `return` or thrown error added later can skip it, which matters most for untrusted files, where errors are common.
- **No nesting:** three documents need three `using` lines, not three nested `try` blocks, and they're freed in reverse order.

Compared with leaving documents to the garbage collector, `using` frees memory at a known point, when the block ends. A server's memory then stays flat from one request to the next.

A freed handle refuses further calls with the error `disposed`, so a document used after its block ends fails at once and names the problem.

#### `await using` in a Web Worker

`@laminapdf/sdk/worker` opens documents in a Web Worker, so closing one sends a message to that Web Worker. Declare those with `await using`, which waits for the close, or call `await doc.close()`.

#### Where `using` runs

Node 24, Deno, Bun, Chrome 134 and Firefox 141 run `using` as written. Node 22 can't parse it, so compile your code with TypeScript or esbuild first. Safari adds `using` in version 27.3, in beta as of November 2026. Until then, compile your code for Safari too; the [SDK's README](https://www.npmjs.com/package/@laminapdf/sdk) gives the one line TypeScript's output needs there. Where you can't use `using` at all, call `free()` in a `finally` block, as above.

A short script that exits right away can skip freeing, since the process gives all its memory back. Rust needs none of this: a `Document` frees its memory when it goes out of scope.

### Three modules in JavaScript

In JavaScript, Lamina PDF is WebAssembly, split into three modules so a page downloads only what it uses:

- **Base:** open, read, edit and save; vector and image pages.
- **Extract:** everything in base, plus text extraction.
- **Text:** everything in base, plus fonts, shaped text and extraction.

`init()` loads the base module, and `init({ text: true })` or `init({ extract: true })` loads one of the others. Call `loadText()` or `loadExtract()` to add a module later, when a page first needs it. Rust has one crate, with features instead.

*The three modules come in @laminapdf/wasm, under @laminapdf/sdk.*

`@laminapdf/sdk` depends on `@laminapdf/wasm`, whose WebAssembly the SDK loads as three modules: base, extract and text. `@laminapdf/viewer` depends on `@laminapdf/sdk`, on `@laminapdf/render` and on both renderers that implement it, `@laminapdf/render-pdfium` and `@laminapdf/render-hayro`. In Rust, the API is one crate, `laminapdf`, with features instead of modules.

## Pages and coordinates

Points from the top-left corner of the page as it's displayed, y going down, and pages numbered from 0.

Every position you pass Lamina PDF is in [page space](/reference/glossary.md#page-space): points measured from the top-left corner of the page, with y going down. It's the way a screen or a sheet of paper reads, so a number means the same thing in every part of the API.

### Points

A point is 1/72 of an inch. An A4 page is about 595 × 842 points, and a US Letter page is 612 × 792. Some pages set a [user unit](/reference/glossary.md#user-unit), which scales the file's own units; Lamina PDF applies it, so a point is always 1/72 inch.

### The top-left corner of the page you see

The origin is the top-left corner of the page as a viewer displays it: its visible area (its [crop box](/reference/glossary.md#crop-box)), turned the way the page is rotated. So `[72, 96]` is one inch from the left edge and 96 points from the top, whichever way the page is rotated in the file.

For text, the second number is the baseline, the line the letters sit on. Letters reach up from it, and descenders such as "g" and "p" hang below it.

This app places "Hello, world!" one inch from the top-left corner, with its baseline one text size lower:

**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)

### Pages count from 0

The first page is page 0 everywhere: `doc.page(0)`, a link's target, a page label's start.

### PDF's own coordinates

Inside the file, PDF measures from the bottom-left corner with y going up, before rotation. That's [user space](/reference/glossary.md#user-space). Lamina PDF converts for you, so you only meet it in Rust, in names that contain `UserSpace` or `user_space`.

*Page space starts at the top-left corner you see; PDF's user space starts at the bottom-left, before rotation.*

On an upright US Letter page, 612 by 792 points, page space starts at the top-left corner with y going down, and PDF's user space starts at the bottom-left corner with y going up. The point `[72, 96]` is one inch from the left edge and 96 points from the top, on the baseline of a heading whose box runs from `[72, 72]` to `[272, 100]`. With `/Rotate 90` a viewer shows the same page on its side, 792 by 612 points. Page space still starts at the top-left corner you see, so `[72, 96]` lands in the same place on the screen. User space starts at that corner too, with its x axis going down and its y axis going right. The heading in the file now runs down the right edge, from `[692, 72]` to `[720, 272]` in page space.

## Errors and warnings

One coded error shape on every surface, and warnings for what Lamina PDF repaired.

Real PDFs are often damaged, so Lamina PDF separates a call that failed from one that worked around a problem. An error stops the call. A warning lets it finish and tells you what was repaired, dropped or approximated. Both carry a stable code your program can branch on.

### Errors stop the call

In TypeScript an error is a `LaminaPdfError`, and in Rust it's a `laminapdf::Error`. Branch on its `code`, never on its `message`: `isLaminaPdfError(e, "wrong-password")` checks the code and narrows the type in one step.

### Warnings say what was repaired

A warning means the call went ahead, but Lamina PDF had to repair, drop or approximate something in the file. Read them with `doc.warnings` in TypeScript or `doc.warnings()` in Rust. Show them to the user when the difference matters, such as a page that may not look the way its author intended.

### Every surface has the same fields

Errors and warnings have the same fields in TypeScript and Rust: `code`, `kind`, `message`, `hint`, `location`, `data` and `docsUrl`. A usage error can also carry `didYouMean`, the closest names to one Lamina PDF didn't recognise. `toJSON()` in TypeScript gives the same object as `serde` does in Rust, so a server and a browser can pass them to each other unchanged.

*A call stops with an error or completes with warnings, and both carry the same core fields.*

A call either stops with a `LaminaPdfError` or completes, with any warnings on `doc.warnings`. Errors and warnings carry the same fields: `code`, `kind`, `message`, `hint`, `location`, `data` and `docsUrl`; an error can also carry `didYouMean`. Text from the document goes only in `data`, never in `message` or `hint`.

- **`kind` sorts errors by who can fix them**, such as `input`, `limit`, `usage`, `state` or `io`. For example, a server returns a 4xx status for `input` and `limit` and a 5xx for the rest, as the [Cloudflare Workers quick start](/quick-start/workers.md) does.
- **Text from the document is untrusted**, so it never appears in `message` or `hint`. It goes only in `data`, where you can escape it before you show it.

This example opens someone else's file and returns the error's code and hint as a value, instead of letting the error escape:

`packages/sdk/examples/open-untrusted.ts`:

```ts
// Open bytes from someone else: an optional password, tighter limits than the defaults, and the
// outcome as a value rather than an exception. The example writes nothing: it returns what it found.
import { Document, isLaminaPdfError } from "@laminapdf/sdk";

const MiB = 1024 * 1024;
/** Limits for an upload endpoint: each decoded stream, and all of them together. */
const LIMITS = { maxStreamDecoded: 16 * MiB, maxDecodedTotal: 64 * MiB } as const;

/** What opening a file gave: its page count and warning codes, or why it didn't open. */
export type Opened =
  | { readonly ok: true; readonly pages: number; readonly warnings: readonly string[] }
  | { readonly ok: false; readonly code: string; readonly hint: string | undefined };

/** Opens `bytes`, with `password` if the file needs one, under {@link LIMITS}. Needs `init()`. */
export function openUntrusted(bytes: Uint8Array, password?: string): Opened {
  try {
    using doc = Document.open(bytes, { ...(password === undefined ? {} : { password }), limits: LIMITS });
    // Repairs and dropped values are warnings: the file opened, but not exactly as written.
    return { ok: true, pages: doc.pageCount, warnings: doc.warnings.map((w) => w.code) };
  } catch (e) {
    // `password-required`, `wrong-password`, `not-pdf`, `limit-exceeded`, …: a coded error whose
    // message and hint never contain text from the file. Anything else is a bug: let it throw.
    if (isLaminaPdfError(e)) return { ok: false, code: e.code, hint: e.hint };
    throw e;
  }
}
```

The [error and warning codes](/reference/codes.md) list every code with its kind, a summary and a hint.

Next: make a PDF with [text and fonts](/guides/fonts-and-text.md).

## What Lamina PDF writes and what it borrows

Lamina PDF writes the parts that decide a PDF's bytes, borrows the rest from permissive projects, and pins and checks everything it borrows.

Add `@laminapdf/viewer` to your app, and it downloads about 2 MB of WebAssembly from a project called EmbedPDF. That WebAssembly is PDFium, the C++ engine behind Chrome's PDF viewer. You may wonder why a Rust library ships someone else's C++, and what else comes along with it. Lamina PDF follows one rule: it writes the parts that decide what your PDF contains. It borrows the rest only from permissively licensed projects that do the job better, and it pins and checks every borrowed piece.

### Lamina PDF writes the parts that decide your bytes

Lamina PDF's own Rust code reads, edits and saves your PDFs. Those parts take files from strangers, and they decide every byte of the file you save. A bug there corrupts documents or breaks signatures, so Lamina PDF owns them. Rust also keeps that code memory-safe while it reads damaged or hostile files. And because Lamina PDF wrote it, the same input gives the same bytes in a browser, on a server and inside a Cloudflare Worker.

### It borrows the work others already do well

Fonts and text shaping are deep problems with good open-source answers, so Lamina PDF reuses them. `skrifa` reads font files, `subsetter` cuts them down to the glyphs you use, and HarfRust shapes Arabic, Hindi and other scripts. ICU4X finds line breaks, and `pdf-writer` writes PDF syntax. Each one is permissively licensed Rust that compiles to WebAssembly. Lamina PDF measured krilla, a complete PDF generator built on the same crates. But krilla can't add content to a file you opened, so Lamina PDF builds on the crates beneath it.

### Drawing pages is the one job it hands to PDFium

Lamina PDF hands one big job to another project: turning pages into pixels. Real-world PDFs often break the specification, and PDFium draws them for everyone who opens a PDF in Chrome. Lamina PDF measured the alternative, hayro, a renderer written in Rust. It drew 91% of 2,196 test pages the same as PDFium or close to it, and most of the rest went wrong on fonts and annotations. A viewer that becomes an editor needs that fidelity from the start, so PDFium draws the pages. `@embedpdf/pdfium` is PDFium compiled to WebAssembly.

### PDFium only draws, and only in a Web Worker

PDFium is C++ reading files you didn't write, so Lamina PDF keeps it at arm's length. The viewer runs it inside a Web Worker, away from your page. PDFium never changes the document either: every edit goes through Lamina PDF, which also writes the saved file. Text, selection and links come from Lamina PDF's own model of the file, never from the renderer. Lamina PDF also checks that the two agree: its tests compare each page's size and every character's position with PDFium's. [How a page is drawn](/concepts/drawing-pages.md) shows the two side by side.

### You pay for PDFium only when you show pages

`@laminapdf/sdk`, the package that creates, reads and edits PDFs, depends only on `@laminapdf/wasm`, Lamina PDF's own WebAssembly. PDFium comes only with `@laminapdf/render-pdfium` and the viewer built on it. For pages as pixels on a server or in a Cloudflare Worker, `@laminapdf/render-hayro` is the lighter choice: pure Rust, with no C++, and a smaller download than PDFium. Every night, Lamina PDF's tests draw thousands of pages with both renderers, so hayro can take over once it matches PDFium.

### Every dependency is permissively licensed

Lamina PDF is `MIT OR Apache-2.0`, so you can use it in a closed product or a paid service. That promise only holds if every dependency allows the same. So Lamina PDF accepts no GPL, AGPL or LGPL code in anything it ships, and a licence check enforces the rule on every change. MuPDF is a fine PDF engine, but it is AGPL, so Lamina PDF never uses it, in any form. Copyleft tools such as veraPDF run as separate programs in Lamina PDF's tests and are never shipped.

### Everything borrowed is pinned and checked

A dependency can change under you, so Lamina PDF's lockfiles pin every one to an exact version. For PDFium, Lamina PDF goes further: the build checks the SHA-256 of `pdfium.wasm`, and any other file fails the build. `@embedpdf/pdfium` ships no notices for the libraries compiled into it, such as libpng, zlib and FreeType. So `@laminapdf/render-pdfium` includes a third-party notices file, and an app that bundles it ships that file too. An update to PDFium arrives as its own reviewed change, and the next release picks up its security fixes.

### What this means for your app

You can build Lamina PDF into closed software, and `@laminapdf/sdk` brings no third-party engine with it. Add the viewer when you need to show pages, and ship PDFium's notices file with it. Next, see [how Lamina PDF thinks about a PDF](/concepts/how-lamina-thinks.md), or start with [your first PDF](/start/first-pdf.md).

## How a page is drawn

A renderer turns a page into pixels; Lamina PDF reads the page's text, links and selection itself, from the same bytes.

Two readers go through every page you show. A renderer, PDFium or hayro, turns the page into pixels. Lamina PDF's own model of the file gives you everything you can select, search or click: the text, the links and the selection boxes. Both read the same bytes.

*A renderer draws the pixels; Lamina PDF reads the text from the same bytes.*

Two readers use your PDF's bytes. To draw, a render request names the page, the scale, the tile to draw (its clip) and a rotation. The request becomes a tile plan, which fixes the size in pixels, and a renderer, PDFium or hayro, draws the tile as RGBA pixels. Text, links and selection never come from the renderer. Lamina PDF reads them from its own model of the same bytes, the model that also edits and saves the file.

### You ask for a tile, and get RGBA pixels back

A render request names the page, the scale in pixels per point, and optionally a clip and a rotation. The clip is the part of the page you want, as a rectangle in pixels: a viewer asks for tiles of a large page rather than the whole page at once, so it only draws what's on screen. A scale of 2 draws 144 pixels per inch, sharp on most screens.

Before it draws, the renderer turns the request into a tile plan: the whole page's size in pixels after the rotation, and the tile inside it. The renderer checks the tile against its limits first: by default, a tile wider or taller than 16,384 pixels, or larger than about 16.7 million pixels, fails with `render-too-large` instead of filling your memory. The renderer then draws the tile as straight RGBA, four bytes a pixel, row by row from the top-left corner.

This example draws a page with hayro and reads the same page's text:

`packages/sdk/examples/draw-page.ts`:

```ts
// Draws one page to pixels and reads the same page's text, to show who does which job: a renderer
// turns the page into RGBA pixels, and Lamina PDF reads the text from its own model of the file.
// Both read the same bytes. In Node, load the hayro renderer with the module's bytes:
//
//   const wasm = fileURLToPath(import.meta.resolve("@laminapdf/wasm/lamina_pdf_render_hayro.wasm"));
//   const renderer = await initHayro(readFileSync(wasm));
//
// Text needs Lamina PDF's text or extract module: `await init({ text: true })`.

import { bytesSource, type RenderBackend } from "@laminapdf/render";
import { Document } from "@laminapdf/sdk";

/** Pixels per point: 2 draws at 144 dpi, sharp on most screens. */
const SCALE = 2;

/** One page as pixels, with its text beside them. */
export interface DrawnPage {
  readonly width: number;
  readonly height: number;
  /** Straight RGBA, four bytes a pixel, row by row from the top-left corner. */
  readonly pixels: Uint8ClampedArray;
  readonly text: string;
}

/** Draws page `index` of `bytes` with `renderer` and reads its text with Lamina PDF. */
export function drawPage(renderer: RenderBackend, bytes: Uint8Array, index: number): DrawnPage {
  // The renderer draws the page and nothing else: it never supplies text, links or selection.
  using drawing = renderer.open(bytesSource(bytes));
  const { width, height, pixels } = drawing.render({ page: index, scale: SCALE });
  // The text comes from Lamina PDF, which also edits and saves the file, so what you select is what
  // an edit changes.
  using doc = Document.open(bytes);
  const text = doc.page(index).text().text();
  return { width, height, pixels, text };
}
```

### The text never comes from the renderer

A renderer draws glyphs, but its idea of the text can differ from the file's: it may guess the order of letters or lose the characters behind a ligature. So Lamina PDF reads text, links and selection from its own model of the file, the same model that edits and saves it. What you select is what `page.text()` returns and what an edit changes.

The two readers can still disagree on where a glyph sits, since each reads the fonts its own way. Lamina PDF's tests compare each page's size and every character's position with PDFium's, and a difference becomes a bug to fix.

### PDFium in the browser, hayro on servers

PDFium, the engine behind Chrome's PDF viewer, draws the pages in the viewer. It runs in a Web Worker, away from your page, and only draws: it never changes the document. hayro is a renderer written in Rust. It's the lighter choice on a server or in a Cloudflare Worker, and it draws in the tests that compare pages. [What Lamina PDF writes and what it borrows](/concepts/dependencies.md) explains why each one is there.

When a page draws wrong or a renderer fails, see [Troubleshooting rendering](/troubleshooting/rendering.md).

Next, see [how to compare pages in tests](/guides/test-generated-pdfs.md), which draws two PDFs and counts the pixels that differ.
