Skip to content
Lamina PDF
0.9.0
GitHub
Open the web app

Recipes, on one page

This page shows every Recipes page in order. Read offline lists every section and the whole guide as one PDF.

Recipes

Each recipe is a complete program to copy: what it makes, the code, how it works and what to change. Pick the one closest to the document you need, and change it from there.

Most recipes exist twice, in Rust and in TypeScript, and both write exactly the same bytes. Lamina PDF’s tests check that on every change, in Rust and in every JavaScript runtime: Node, Chromium, Firefox, WebKit, Deno, Bun and workerd. Each recipe shows the tested code, and its reference PDF is the file that code writes. To test your own PDFs the same way, see Test the PDFs you generate.

To run a Rust recipe from a checkout of Lamina PDF, use cargo run -p laminapdf --example <name>. Its header comment lists the arguments it takes, such as the font or image files it reads.

  • Generate, then edit: open a file’s bytes, change its metadata and save incrementally.
  • Edit the metadata: a title, authors and keywords in both copies a PDF keeps, checked before the save.
  • Choose how a PDF opens: the page and zoom, the panel beside the page and the title in the window.
  • Edit the bookmarks: add, move and style bookmarks, and name places links jump to.
  • Add a contents page: a page listing the bookmarks, each with its page label and a link there.
  • Add links: link a drawn box or a line of text to a page or a web address, with a description screen readers read.
  • Mark up a page: highlight text, leave a sticky note and propose a replacement word, drawn the same in every reader.
  • Answer a review: read the comments as threads, reply to a question and mark a highlight done.
  • Fill a form from JSON: fill a form’s fields from your own data in one change, with its totals worked out.
  • Check for an XFA form: find out whether a form is an XFA form, and make a static one show the same answers in every app.
  • Flatten a filled form: draw a form’s answers into its pages, so they show the same everywhere and can’t be changed.
  • Flatten comments: draw every comment and mark into its page, so a copy prints the same everywhere.
  • Print a comment summary: a new, accessible PDF listing every comment, each page drawn beside its comments.
  • Draw on a page: freehand ink, shapes, arrows and polygons, each with a description screen readers read.
  • Add a text box: type on a page in a text box or a callout, with bold and italic words and any font.
  • Stamp a page and attach a file: approve a page with a stamp, attach a file to a spot on it, and play sound comments.
  • Place images and shapes on a page: add a logo, a picture, a shape or a page of another PDF as page content, and move or remove it after a save.
  • Add text to a page: type on a page as page content, in any font and script, with fallback fonts for symbols, then change or remove it after a save.
  • Add watermarks, headers and Bates numbers: mark every page with a watermark, a header and footer with page numbers, and Bates numbers, then change or remove them after a save.
  • Record your own metadata: properties of your own in the XMP metadata, in a PDF/A file that stays valid.
  • Organise pages: delete, move, insert and rotate pages in one edit, with the bookmarks and links that pointed at a deleted page sent on.
  • Duplicate pages: copy a page so the copy has form fields, annotations and tags of its own.
  • Edit what a page draws: move, resize, delete and reorder the shapes, text and images a page already draws.
  • Edit the text a page shows: change or delete a run of text in the font it is set in.
  • Change how text looks: make a run bold, coloured or underlined, change its font or size, and align its lines.
  • Edit a tagged PDF: edit an accessible file with its tags kept up to date, and check its PDF/A and PDF/UA claims before saving.
  • Crop pages: crop every page by the same margins, whatever its size or rotation.
  • Resize pages: put every page on new paper, scaled to fit or extended, and turn pages to portrait or landscape.
  • Copy pages between PDFs: copy pages in from another file, replace a page, or make a new PDF from some pages.
  • Merge and split PDFs: merge files into one with a bookmark for each, or split a file by chapter.

Next: Hello, world, the smallest PDF Lamina PDF writes.

Hello, world

You’ll make the smallest PDF Lamina PDF writes: one A4 page that says “Hello, world!” in Helvetica. Start from it to check that a new setup works, or as the skeleton of a document of your own.

The function builds the page and returns the PDF’s bytes. In TypeScript it needs the text module, init({ text: true }). Both languages write the same bytes:

packages/sdk/examples/hello.ts
// The smallest document: one A4 page with a line of text in a standard 14 font.
import { Builder, type BuilderOptions, Font } from "@laminapdf/sdk";
/**
* The document's bytes. Needs `init({ text: true })`.
*
* @param options - can fix the file ID, the producer and the creation date, so that the same
* input gives the same bytes on every run.
*/
export function hello(options: BuilderOptions = {}): Uint8Array<ArrayBuffer> {
using b = new Builder(options);
const page = b.page("A4");
// Page space: points from the top-left corner, y down; `at[1]` is the text's baseline.
page.surface().text("Hello, world!", { font: Font.standard("Helvetica"), size: 24, at: [72, 96] });
page.finish();
using doc = b.finish();
return doc.save();
}
Page 1 of hello.pdf
Open hello.pdf (1 page, 1 KB)

The result is one page with the line near its top-left corner. The Result tab shows it, with a link to the PDF.

  • The builder makes an A4 page, and the page’s surface is what you draw on.
  • at is in points from the top-left corner of the page, with y going down. Its second number is the text’s baseline. See Pages and coordinates.
  • Helvetica is one of the standard 14 fonts, which every PDF viewer has, so the PDF embeds no font.
  • Finishing the builder gives a document, and saving the document gives its bytes. using in TypeScript frees both as soon as the function ends.
  • The text and where it goes: change the string, the size and at.
  • The page size: name another size, such as "Letter", or pass [width, height] in points.
  • The font: for characters outside the standard 14 fonts’ Latin set, embed a font. See Text and fonts.
  • A file ID or a date of your own: pass them in the builder’s options. Without them, the file ID is a hash of the content and the PDF has no creation date, so the same code writes the same bytes on every run.

Next: an invoice, with an embedded font and a table of line items.

An invoice

You’ll make a one-page invoice: a heading, an address, a table of line items with right-aligned amounts, and a total. It’s tagged, so a screen reader reads it in order. Start from it for any document built around a table, such as a quote or a receipt.

The function takes a font file, draws the invoice and returns the PDF’s bytes. In TypeScript it needs the text module, init({ text: true }). Both languages write the same bytes:

packages/sdk/examples/invoice.ts
// An invoice that screen readers can follow, with an embedded font and a table of line items.
// The heading, the address, the table of items and the total are tagged, so a screen reader
// reads them in order.
import { Builder, type BuilderOptions, Font, PAGE_SIZES, type Rect, type Surface } from "@laminapdf/sdk";
const ITEMS: readonly (readonly [item: string, qty: number, price: number])[] = [
["Widgets, blue (W-100)", 3, 12.0],
["Gadget with fine-tuned dials", 1, 79.9],
["Café-grade sprockets", 12, 1.25],
["Delivery", 1, 4.5],
];
const ADDRESS = "Acme Widgets Ltd · 1 Example Street · London";
const PAGE = "A4";
const [PAGE_WIDTH] = PAGE_SIZES[PAGE];
const MARGIN = 56;
const RIGHT_EDGE = PAGE_WIDTH - MARGIN;
const TITLE_AT = [MARGIN, 80] as const;
const ADDRESS_AT = [MARGIN, 100] as const;
const TITLE = 24;
const BODY = 11;
const FIRST_ROW = 160;
const ROW_HEIGHT = 24;
/** The quantity's and the amount's columns, each a width ending this far left of the right edge. */
const COLUMNS = [
[40, 169],
[100, 0],
] as const;
/** A cell's box starts this far above its row's baseline and is this tall. */
const CELL_RISE = 12;
const CELL_HEIGHT = 16;
/**
* The document's bytes, in `fontBytes` (a TrueType or OpenType file). Needs `init({ text: true })`.
*
* @param options - can fix the file ID, the producer and the creation date.
*/
export function invoice(fontBytes: Uint8Array, options: BuilderOptions = {}): Uint8Array<ArrayBuffer> {
using b = new Builder({ ...options, tagged: true });
const font = Font.fromBytes(fontBytes);
const bold = Font.standard("Helvetica-Bold");
// Registered up front, in this order, so the embedded font is the document's first.
b.font(font);
b.font(bold);
const page = b.page(PAGE);
const s = page.surface();
s.text("Invoice 42", { font: bold, size: TITLE, at: TITLE_AT, tag: "H1" });
s.text(ADDRESS, { font, size: BODY, at: ADDRESS_AT, tag: "P" });
items(s, font);
const total = ITEMS.reduce((sum, [, qty, price]) => sum + qty * price, 0);
const box = cell(COLUMNS[1], rowBaseline(ITEMS.length));
s.textBox(`Total € ${total.toFixed(2)}`, { font, size: BODY, box, align: "end", tag: "P" });
page.finish();
b.metadata({ title: "Invoice 42", author: "Acme Widgets Ltd" }).lang("en-GB");
using doc = b.finish();
return doc.save();
}
/** The table of line items: what, how many, and the amount, right-aligned. */
function items(s: Surface, font: Font): void {
s.tag("Table", (s) => {
ITEMS.forEach(([item, qty, price], row) => {
const y = rowBaseline(row);
const cells = [
[String(qty), COLUMNS[0]],
[`€ ${(qty * price).toFixed(2)}`, COLUMNS[1]],
] as const;
s.tag("TR", (s) => {
s.text(item, { font, size: BODY, at: [MARGIN, y], tag: "TD" });
for (const [text, column] of cells) {
s.textBox(text, { font, size: BODY, box: cell(column, y), align: "end", tag: "TD" });
}
});
});
});
}
/** The baseline of row `row` of the table. */
function rowBaseline(row: number): number {
return FIRST_ROW + ROW_HEIGHT * row;
}
/** The box of a cell in `column` (width, distance from the right edge) on the row at `baseline`. */
function cell([width, inset]: readonly [number, number], baseline: number): Rect {
return [RIGHT_EDGE - inset - width, baseline - CELL_RISE, width, CELL_HEIGHT];
}
Page 1 of invoice.pdf
Open invoice.pdf (1 page, 12 KB)

The result is one A4 page with its body set in Noto Sans. The Result tab shows it, with a link to the PDF.

  • The body uses your font file, and Lamina PDF embeds only the glyphs the invoice draws. The heading uses Helvetica Bold, one of the standard 14 fonts, so it embeds nothing.
  • Each quantity and amount is a text box aligned to its end, so the numbers line up on the right. cell works out each box from its column’s width and its distance from the right margin.
  • tagged: true (with_tagged(true) in Rust) gives the document a structure for screen readers. The tag option and s.tag(…) make the heading an H1, the address and the total each a paragraph (P), and the items a Table of rows (TR) and cells (TD).
  • metadata sets the title and author, and lang("en-GB") tells a screen reader which language to speak.
  • The line items: edit ITEMS. Each row sits ROW_HEIGHT points below the one before, and the total follows the last row.
  • The columns: each pair in COLUMNS is a column’s width and its distance from the right margin, in points.
  • The currency: change the € in the amount and total strings. Your font needs a glyph for the new symbol, or drawing fails with missing-glyph. See Text and fonts.
  • A PDF/UA-1 invoice: add profiles: ["PDF/UA-1"] (with_profile(Profile::PdfUa1) in Rust) to check the rules for accessible PDFs. PDF/UA-1 needs every font embedded, so load a bold font file for the heading. See Accessible PDFs.

Next: multilingual text, with five scripts, each in its own embedded font.

Fill an invoice from JSON

You’ll make an invoice from two JSON files: a template with the heading, text and a table, and the data with the number, line items and total. A program or a language model can write either, and the schema checks them before anything is drawn.

The template is a document with placeholders that point into the data. This table row is repeated once per line item, and each cell takes a value from the current item:

"rows": [{
"$each": "/items",
"do": { "cells": [
{ "text": { "$item": "/item" } },
{ "text": { "$item": "/description" } },
{ "text": { "$item": "/quantity" }, "align": "end" },
{ "text": { "$item": "/amount" }, "align": "end" }
] }
}]

Each example fills the template from the data, gives it its two fonts by the names it uses, and returns the PDF’s bytes. Both write the same bytes:

packages/sdk/examples/invoice-from-json.ts
// An invoice from a JSON template and its data: the template lays out the heading, the text and
// a table, and the data fills in the number, the line items and the total.
//
// The table runs onto a second page with its header row repeated, and the total stays with the
// last rows. The template names its two fonts, `regular` and `bold`; their bytes come beside it.
// The output is checked against PDF/UA-1, which the template asks for.
import { Builder, type BuilderOptions, type FlowTemplate, Font } from "@laminapdf/sdk";
/**
* The invoice's bytes. Needs `init({ text: true })`.
*
* @param template - the invoice template, a `laminapdf.document/1` document with placeholders.
* @param data - the values its placeholders read.
* @param regular - the font the template calls `regular`.
* @param bold - a collection whose second face (index 1) is the one it calls `bold`.
* @param options - can fix the file ID, the producer and the creation date.
*/
export function invoiceFromJson(
template: FlowTemplate,
data: unknown,
regular: Uint8Array,
bold: Uint8Array,
options: BuilderOptions = {},
): Uint8Array<ArrayBuffer> {
// The builder checks the profiles it is given: the ones the template asks for.
using b = new Builder({ ...options, profiles: template.profiles ?? [] });
b.flow(template, {
data,
fonts: { regular: Font.fromBytes(regular), bold: Font.fromCollection(bold, 1) },
});
using doc = b.finish();
return doc.save();
}

The result is two A4 pages that meet PDF/UA-1. The table’s header row repeats at the top of the second page, and the total stays with the last rows. The Result tab shows both pages, with a link to the PDF.

  • fill (in TypeScript, builder.flow given data) replaces each placeholder with the value it points to, then reads the result as a document. A pointer is a path into the data (RFC 6901): /invoice/number is the number inside invoice, and /items/0 the first line item.
  • { "$data": "/total" } puts a value from the data where text belongs, and { "$item": "/amount" } puts one from the current item of an $each.
  • { "$each": "/items", "do": … } repeats a block or a table row once per item of a list. { "$if": "/invoice/paid", "do": … } keeps its block only when that value is there and isn’t false or null. This invoice’s data says it isn’t paid, so the “Paid in full” line is left out.
  • The template names its text styles once, such as body and strong, and each style names a font. The fonts’ bytes come beside the template, through Resources in Rust and fonts in TypeScript, so the template holds no files.
  • The template asks for PDF/UA-1 in its profiles, so each example passes them to the builder, which checks the rules for accessible PDFs before it writes anything.
  • The line items: edit the data. The template doesn’t change, and the table runs onto as many pages as the items need.
  • Totals, dates and currency: put them in the data already formatted, such as "total": "4,001.10 €". Templates have no arithmetic or formatting by design: whatever writes the data does the sums.
  • A misspelt key: reading the document fails with invalid-document. Its data.pointer names the value, such as /blocks/2/spaceAftr, and its didYouMean the closest key the format knows. In TypeScript, tsc refuses a misspelt key in a template you write in your code as a FlowTemplate; a template read from a file is checked when flow reads it.
  • A value the data lacks: filling fails with template-data-missing and the pointer the template used, so a gap never reaches the PDF.
  • Check what a model writes: validate the document against laminapdf.document/1’s schema. The laminapdf crate and @laminapdf/sdk both ship it as docs/schemas/document.schema.json.

The command-line tool fills the template and lays it out in one command, giving each font by the name the template uses:

Terminal window
laminapdf build invoice.json --data invoice-data.json --font regular=NotoSans-Regular.ttf --font bold=NotoSans-RegularBold.ttc#1 -o invoice.pdf

#1 takes the bold face of a font collection. Make and change PDFs has the rest.

Next: Pages that flow, with every block a document can hold.

Turn Markdown into a PDF

You’ll turn a report written in Markdown into an accessible PDF: headings, lists, a table that runs across pages, a photo, footnotes, a contents page, and paragraphs in Arabic and Hindi. Use it for anything you already write in Markdown, such as notes, documentation or a report an LLM drafted.

From the command line, one command builds it:

Terminal window
laminapdf build report.md -o report.pdf \
--font regular=NotoSans-Regular.ttf --font bold=NotoSans-Bold.ttf \
--font fallback=NotoSansArabic-Regular.ttf --font fallback=NotoSansDevanagari-Regular.ttf \
--profile pdf-ua-1

The command reads the images the Markdown names from the folder the Markdown is in. Add --json for a report of the pages, the size and anything the PDF left out.

In code, the function passes the Markdown, the fonts and the photo to builder.markdown (Builder::markdown in Rust) and returns the PDF’s bytes. In TypeScript it needs the text module, init({ text: true }). Both languages write the same bytes:

packages/sdk/examples/markdown-to-pdf.ts
// A report written in Markdown, turned into tagged pages that flow: headings, paragraphs with
// emphasis, code and links, a photo, lists and a task list, a block quote, a table that runs
// across pages, a code block, footnotes, and paragraphs in Arabic and Hindi.
//
// The front matter gives the title and language, a contents page lists the headings, and the
// output meets PDF/UA-1, so every font is embedded. The builder reads no files: the fonts and the
// one photo the Markdown names are passed in, and nothing is fetched.
import { Builder, type BuilderOptions, Font, Image } from "@laminapdf/sdk";
/** The fonts the report is set in: Latin, a bold face, Arabic and Devanagari. */
export interface ReportFonts {
readonly regular: Uint8Array;
/** A collection whose second face (index 1) is the bold one. */
readonly bold: Uint8Array;
readonly arabic: Uint8Array;
readonly devanagari: Uint8Array;
}
/**
* The report's bytes. Needs `init({ text: true })`.
*
* @param markdown - the report's Markdown.
* @param fonts - the fonts to set it in.
* @param photo - the JPEG the Markdown shows as `photo.jpg`.
* @param options - can fix the file ID, the producer and the creation date.
*/
export function markdownToPdf(
markdown: string,
fonts: ReportFonts,
photo: Uint8Array,
options: BuilderOptions = {},
): Uint8Array<ArrayBuffer> {
using b = new Builder({ ...options, profiles: ["PDF/UA-1"] });
const report = b.markdown(markdown, {
fonts: {
regular: Font.fromBytes(fonts.regular),
bold: Font.fromCollection(fonts.bold, 1),
fallbacks: [Font.fromBytes(fonts.arabic), Font.fromBytes(fonts.devanagari)],
},
images: { "photo.jpg": Image.jpeg(photo) },
// A5 pages, so the table runs across two of them, with the page number in the footer.
page: { size: "A5", footer: { center: "Page {page} of {pages}" }, furnitureSize: 8 },
contents: 2,
});
using doc = b.finish();
const [warning] = doc.warnings;
if (warning !== undefined) throw new Error(`the Markdown has something the PDF leaves out: ${warning.code}`);
if (report.pages.length === 0) throw new Error("the report has no pages");
return doc.save();
}
Page 1 of markdown_to_pdf.pdf
Open markdown_to_pdf.pdf (4 pages, 52 KB)

The result is four A5 pages that meet PDF/UA-1. The Result tab shows them, with a link to the PDF.

  • Each Markdown construct becomes the block you would lay out by hand: a # heading becomes a heading, a list a list, and a table a table whose header row repeats on each page. The pages that flow guide shows those blocks.
  • The front matter, plain key: value lines between two --- lines, sets the title, language, author and subject. A screen reader uses the language to choose its voice.
  • The fonts come by role: body text, bold (headings too), italic, code, and fallbacks for characters the others lack. Here the Arabic and Devanagari fonts are fallbacks, so each paragraph in those scripts finds its letters.
  • Nothing is fetched. An image you don’t pass, or a remote one, is left out with the warning markdown-image-missing, and raw HTML with markdown-html-ignored. Both name a position in the Markdown, never its text.
  • The PDF is tagged: headings, lists, tables, figures with the image’s text as their alternate text, and footnotes, in reading order.
  • Latin text only: leave out the fonts, and the text is set in Helvetica and Courier, which every PDF reader has. They aren’t embedded, so PDF/UA-1 refuses them with font-not-embedded; drop the profile, or pass your own fonts.
  • The page size: --page-size letter on the command line, page: { size: "Letter" } in TypeScript, or a PageTemplate in Rust. The template also sets the margins, a header and the footer.
  • No contents page: remove contents (with_contents in Rust). The command line never adds one.
  • An AI agent: laminapdf mcp --root DIR --allow-write serves the laminapdf_build tool to agents that speak MCP. It takes the Markdown inline or as a file, reads fonts and images only inside DIR, and writes the PDF there as a new file. Inline Markdown reads no images; pass a file for those.

Next: a PDF/UA report, drawn block by block instead of written in Markdown.

Multilingual text

You’ll put five scripts on one page: Latin, Arabic, Devanagari, Hebrew and Chinese, each as a single line and as a paragraph wrapped in a box. Start from it whenever your text goes beyond Latin, or mixes left-to-right and right-to-left writing.

The function takes one font file per script, draws each script’s line and paragraph, and returns the PDF’s bytes. In TypeScript it needs the text module, init({ text: true }). Both languages write the same bytes:

packages/sdk/examples/multilingual.ts
// Five scripts on one page, each as a single line and as a wrapped paragraph. The scripts are
// Latin, Arabic and Hebrew (right to left), Devanagari and simplified Chinese; each is shaped and
// bidi-resolved, and each paragraph wraps in a text box. Each script needs a font that covers it,
// such as the Noto fonts (OFL).
import { Builder, type BuilderOptions, type Direction, Font } from "@laminapdf/sdk";
/** Each script's line, its paragraph and the paragraph's direction, in the order of the fonts. */
export const SCRIPTS: readonly (readonly [line: string, paragraph: string, direction: Direction])[] = [
[
"Latin: the office staff fill the affine waffle flask",
"A paragraph breaks at spaces and fits the width of its box, line by line.",
"ltr",
],
["مرحبا بالعالم السلام عليكم", "مرحبا بالعالم السلام عليكم مرحبا بالعالم السلام عليكم", "rtl"],
["नमस्ते दुनिया। हिन्दी पाठ का परीक्षण", "नमस्ते दुनिया। हिन्दी पाठ का परीक्षण नमस्ते दुनिया।", "ltr"],
["שלום עולם וברוכים הבאים", "שלום עולם וברוכים הבאים שלום עולם וברוכים הבאים", "rtl"],
["你好世界,这是中文字体子集测试。", "你好世界,这是中文字体子集测试。你好世界,这是中文。", "ltr"],
];
const MARGIN = 56;
const FIRST_BASELINE = 80;
/** The distance from one script's line to the next one's. */
const SCRIPT_HEIGHT = 140;
/** The paragraph's box: this far below the line, this wide and this tall. */
const PARAGRAPH_DROP = 14;
const PARAGRAPH_WIDTH = 220;
const PARAGRAPH_HEIGHT = 100;
/**
* The document's bytes. Needs `init({ text: true })`.
*
* @param fonts - one font file per script, in the order of {@link SCRIPTS}.
* @param options - can fix the file ID, the producer and the creation date.
*/
export function multilingual(fonts: readonly Uint8Array[], options: BuilderOptions = {}): Uint8Array<ArrayBuffer> {
if (fonts.length !== SCRIPTS.length) throw new Error(`${SCRIPTS.length} fonts, one per script, are needed`);
using b = new Builder(options);
const loaded = fonts.map((bytes) => Font.fromBytes(bytes));
for (const font of loaded) b.font(font);
const page = b.page("A4");
const s = page.surface();
SCRIPTS.forEach(([line, paragraph, direction], row) => {
const font = loaded[row];
if (font === undefined) return;
const y = FIRST_BASELINE + SCRIPT_HEIGHT * row;
s.text(line, { font, size: 16, at: [MARGIN, y] });
// A narrow box breaks the paragraph into lines; right-to-left paragraphs start at the right.
const box = [MARGIN, y + PARAGRAPH_DROP, PARAGRAPH_WIDTH, PARAGRAPH_HEIGHT] as const;
s.textBox(paragraph, { font, size: 12, box, direction, align: "start" });
});
page.finish();
using doc = b.finish();
return doc.save();
}
Page 1 of multilingual.pdf
Open multilingual.pdf (1 page, 27 KB)

The result is one A4 page, with each script set in its own Noto font. The Result tab shows it, with a link to the PDF.

  • Font.fromBytes (font_bytes in Rust) loads each font, which must cover its script. The builder embeds only the glyphs the page draws.
  • Lamina PDF shapes the text with each font, so Arabic letters join, Devanagari letters combine into clusters and the Latin line forms ligatures.
  • textBox breaks each paragraph into lines that fit its 220-point-wide box. It breaks where Unicode’s line-breaking rules allow: between words, and between Chinese characters.
  • direction: "rtl" (Direction::RightToLeft) makes the Arabic and Hebrew paragraphs right to left, so align: "start" starts their lines at the box’s right edge.
  • Each font is embedded with its ToUnicode mapping, so text copied or extracted from the PDF equals the strings you passed in, ligatures included.
  • Your own scripts: change SCRIPTS and pass one font per row, in the same order. A character the font lacks fails with missing-glyph.
  • The paragraph’s box: PARAGRAPH_WIDTH and PARAGRAPH_HEIGHT set its size. Lines that don’t fit are left out, unless you pass overflow: "error" (Overflow::Error) to fail with text-overflow instead.
  • Alignment and spacing: align also takes "end", "left", "right" or "center", and lineHeight (with_line_height) sets the distance between baselines, 1.2 times the size by default.
  • Ligatures and other OpenType features: features: ["liga=0"] on text or textBox turns the ligatures off. In Rust, call features on the run or with_feature on the text box’s options. See Text and fonts.

Next: images and vectors, with shapes, colour, transparency and two images.

Images and vectors

You’ll draw shapes and images on one A4 page: a rectangle, a circle, a dashed curve, two see-through discs, a photo cut to an ellipse and a rotated gradient that fades out. Start from it for a logo, a chart, the rules of a table or a page with photos.

The function takes a JPEG’s bytes, draws the page and returns the PDF’s bytes. It draws no text, so in TypeScript it needs only the base module, init(). Both languages write the same bytes:

packages/sdk/examples/images-and-vectors.ts
// Images and vector graphics on one A4 page. It draws shapes and a dashed Bézier curve in gray,
// RGB, CMYK and hex colour, overlaps two translucent discs with a blend mode, clips a JPEG to an
// ellipse and rotates an RGBA image with a soft mask. Needs only the base module.
import { Builder, type BuilderOptions, Image, Matrix, type Surface } from "@laminapdf/sdk";
/** The RGBA gradient's side, in pixels. */
const GLOW_SIDE = 16;
/**
* The document's bytes, with `photo` (a JPEG) on the page.
*
* @param options - can fix the file ID, the producer and the creation date.
*/
export function imagesAndVectors(photo: Uint8Array, options: BuilderOptions = {}): Uint8Array<ArrayBuffer> {
using b = new Builder(options);
const jpeg = Image.jpeg(photo);
const glow = Image.rgba(GLOW_SIDE, GLOW_SIDE, gradient());
const page = b.page("A4");
const s = page.surface();
shapes(s);
overlappingDiscs(s);
images(s, jpeg, glow);
page.finish();
using doc = b.finish();
return doc.save();
}
/** A square gradient whose alpha falls off towards the right. */
function gradient(): Uint8Array {
const out = new Uint8Array(GLOW_SIDE * GLOW_SIDE * 4);
for (let y = 0; y < GLOW_SIDE; y++) {
for (let x = 0; x < GLOW_SIDE; x++) out.set([x * 16, y * 16, 200, 255 - x * 15], (y * GLOW_SIDE + x) * 4);
}
return out;
}
/** A rectangle, a circle and a dashed, round-capped Bézier curve. */
function shapes(s: Surface): void {
s.fillColor([0.9, 0.3, 0.2])
.path((p) => p.rect([56, 56, 160, 100]))
.fill();
s.fillColor([0.8, 0.1, 0, 0])
.path((p) => p.circle([330, 106], 50))
.fill();
s.strokeColor("#2a9d8f")
.path((p) => p.moveTo(56, 220).cubicTo(180, 140, 300, 300, 539, 200))
.stroke({ width: 3, cap: "round", dash: [12, 8] });
}
/** Two translucent discs, the second multiplied onto the first. */
function overlappingDiscs(s: Surface): void {
s.save().opacity(0.6, 1).fillColor([0.3]);
s.path((p) => p.circle([120, 330], 60)).fill();
s.blendMode("multiply").fillColor([1, 0.8, 0]);
s.path((p) => p.circle([190, 330], 60))
.fill()
.restore();
}
/** The photo clipped to an ellipse, and the gradient rotated by 30 degrees. */
function images(s: Surface, photo: Image, glow: Image): void {
s.save()
.path((p) => p.ellipse([300, 270, 239, 120]))
.clip();
s.image(photo, [300, 250, 239, 160]).restore();
s.save().transform(Matrix.after(Matrix.translate(150, 520), Matrix.rotate(30)));
s.image(glow, [-60, -60, 120, 120]).restore();
}
Page 1 of images_and_vectors.pdf
Open images_and_vectors.pdf (1 page, 5 KB)

The result is one A4 page with every shape and both images. The Result tab shows it, with a link to the PDF.

  • path(p => …) builds a shape and returns it unpainted. fill and stroke paint it, and clip limits what’s drawn next to its inside. See Shapes, colour and images.
  • A colour of one, three or four numbers from 0 to 1 is gray, RGB or CMYK, and a string such as "#2a9d8f" is hex. Rust has Color::gray, rgb, cmyk and hex.
  • save() and restore() bracket each group of drawings, so the opacity, blend mode, clip and rotation set inside stop at restore().
  • Both discs are 60% opaque, and multiply darkens the area where the second disc covers the first.
  • Image.jpeg embeds the photo as it is, without decoding it. Image.rgba takes raw pixels, and their alpha becomes a soft mask: a second image that holds the transparency.
  • The matrix turns the gradient 30 degrees clockwise, then moves it to (150, 520). The gradient is drawn centred on the origin, so it turns about its own centre. Like every position, the matrix works in page space.
  • A PNG instead of the JPEG: Image.png(bytes) (Image::png in Rust) keeps the PNG’s transparency.
  • A shape with a hole: draw both outlines in one path and fill it with "evenOdd" (FillRule::EvenOdd), so the inner shape stays empty.
  • A filled shape with an outline: fillStroke(rule, style) (fill_stroke in Rust) paints both at once.
  • Another blend mode: "screen" lightens where "multiply" darkens. BlendMode lists all sixteen.
  • Alternate text: pass a description as the third argument of image (figure in Rust), and a screen reader reads it out. See Accessible PDFs.

Next: links and outlines, with four pages joined by links, an outline and page labels.

Turn photos into a PDF

You’ll put photos into one PDF, one A4 page each, every photo fitted inside a 15 mm margin. Use it for scans from a phone, receipts for an expense claim, or pictures to print as one file.

The function passes the photos to imagesToPdf (images_to_pdf in Rust) and returns the PDF’s bytes. In TypeScript it needs the extract or the text module, init({ extract: true }). Both languages write the same bytes:

packages/sdk/examples/images-to-pdf.ts
// Photos into a PDF, one A4 page each, fitted inside the margins.
//
// Each JPEG is embedded as it is, without decoding or compressing it again. A page turns to
// landscape for a wide photo, and a photo that its camera marked as taken sideways is drawn
// upright.
import { Image, type ImagesToPdfOptions, imagesToPdf } from "@laminapdf/sdk";
/** The space around each photo, in millimetres. */
const MARGIN_MM = 15;
/** Points in an inch, and millimetres in an inch. */
const POINTS_PER_INCH = 72;
const MM_PER_INCH = 25.4;
/**
* The document's bytes, one page per photo.
*
* @param photos - the JPEGs, one per page, in order.
* @param options - can fix the file ID, the producer and the creation date.
*/
export function imagesToPdfBytes(
photos: readonly Uint8Array[],
options: Omit<ImagesToPdfOptions, "fit" | "margin"> = {},
): Uint8Array<ArrayBuffer> {
using doc = imagesToPdf(
photos.map((photo) => Image.jpeg(photo)),
{ ...options, fit: "A4", margin: (MARGIN_MM * POINTS_PER_INCH) / MM_PER_INCH },
);
return doc.save();
}
Page 1 of images_to_pdf.pdf
Open images_to_pdf.pdf (2 pages, 6 KB)

The result has two pages: a colour photo and a greyscale one. The Result tab shows them, with a link to the PDF.

  • Each JPEG goes into the file as it is, without decoding or compressing it again, so the page keeps every pixel the camera wrote and the PDF is barely larger than the photos.
  • A PNG is decoded and kept with its transparency.
  • A page turns to landscape for a photo wider than it is tall, and the photo is scaled to fit inside the margins and centred.
  • A phone often stores a photo sideways and records which way is up in its EXIF data. The page shows it the way up the EXIF data says.
  • Another paper size: pass fit: "Letter", or [width, height] in points (ImagePages::Fit(PageSize::LETTER) in Rust).
  • Pages the photos’ own size: leave out fit (ImagePages::ImageSize in Rust). Each page is then its photo’s size at the resolution its file records, or at defaultDpi (72 by default) when the file records none.
  • No margin: leave out margin, and each photo fills its page edge to edge in one direction.
  • PNG images: Image.png(bytes) in place of Image.jpeg(bytes) (Image::png in Rust).

Next: images and vectors, which draws images, paths and transparency on one page.

Element flow

You’ll lay out a report where each part starts below wherever the part before it ended: a title, a summary, optional notes, a photo and a body that runs onto a second page. Use it when the length of your text changes from one document to the next.

The function takes a JPEG’s bytes and the report’s text, and returns the PDF’s bytes. In TypeScript it draws text, so it needs init({ text: true }). Both languages write the same bytes:

packages/sdk/examples/element-flow.ts
// A report whose title, paragraphs and photo each start below wherever the one before ended. Each
// text box reports its `bottom`, and the next element starts a gap below it, so a summary that
// wraps moves everything after it and empty notes take no space. The body continues on new pages
// from the top margin. Needs `init({ text: true })`.
import { Builder, type BuilderOptions, Font, Image, PAGE_SIZES, type Surface, type TextLayout } from "@laminapdf/sdk";
const [PAGE_WIDTH, PAGE_HEIGHT] = PAGE_SIZES.A5;
const MARGIN = 48;
const WIDTH = PAGE_WIDTH - 2 * MARGIN;
const BOTTOM = PAGE_HEIGHT - MARGIN;
const TITLE = 18;
const BODY = 11;
const GAP = 10;
/** The photo's height, for a 3:2 photo across the text column. */
const PHOTO_HEIGHT = WIDTH / 1.5;
/** What the report says. Empty `notes` take no space; blank lines separate the body's paragraphs. */
export interface Report {
readonly title: string;
readonly summary: string;
readonly notes: string;
readonly body: string;
}
/**
* The report's bytes, with `photo` (a JPEG) below its notes.
*
* @param options - can fix the file ID, the producer and the creation date.
*/
export function elementFlow(photo: Uint8Array, report: Report, options: BuilderOptions = {}): Uint8Array<ArrayBuffer> {
using b = new Builder(options);
const fonts = { bold: Font.standard("Helvetica-Bold"), regular: Font.standard("Helvetica") };
const jpeg = Image.jpeg(photo);
let page = b.page("A5");
let y = header(page.surface(), fonts, jpeg, report);
let [rest, newPage] = [report.body.trimEnd(), false];
for (;;) {
const layout = page.surface().textBox(rest, { font: fonts.regular, size: BODY, box: area(y) });
// A clipped box still drew its first lines: the rest goes on a new page, from its top.
const cut = layout.overflow;
if (cut === undefined) break;
if (cut === 0 && newPage) throw new Error("a line of the body is taller than the page");
[rest, y, newPage] = [rest.slice(cut).trimStart(), MARGIN, true];
page.finish();
page = b.page("A5");
}
page.finish();
using doc = b.finish();
return doc.save();
}
/**
* The title with a rule under it, the summary, the notes and the photo, each below the one before;
* returns where the body starts. Text that doesn't fit throws `text-overflow`.
*/
function header(s: Surface, fonts: { bold: Font; regular: Font }, photo: Image, report: Report): number {
const fit = (text: string, font: Font, size: number, top: number) =>
below(s.textBox(text, { font, size, box: area(top), overflow: "error" }), top);
let y = fit(report.title, fonts.bold, TITLE, MARGIN);
// A decoration half a gap above the summary. It's stroked: a fill colour would colour the text too.
s.strokeColor([0.6])
.path((p) => p.rect([MARGIN, y - GAP / 2, WIDTH, 0]))
.stroke();
for (const text of [report.summary, report.notes]) y = fit(text, fonts.regular, BODY, y);
if (y + PHOTO_HEIGHT > BOTTOM) throw new Error("the photo doesn't fit below the notes");
s.image(photo, [MARGIN, y, WIDTH, PHOTO_HEIGHT]);
return y + PHOTO_HEIGHT + GAP;
}
/** Where the next element starts: a gap below `layout`'s last drawn line, or `y` if it drew none. */
function below(layout: TextLayout, y: number): number {
return layout.bottom === undefined ? y : layout.bottom + GAP;
}
/** The rest of the page's text column, from `y` down to the bottom margin. */
function area(y: number): [number, number, number, number] {
return [MARGIN, y, WIDTH, Math.max(BOTTOM - y, 0)];
}
Page 1 of element_flow.pdf
Open element_flow.pdf (2 pages, 6 KB)

The result is two A5 pages. The body fills the first page below the photo and finishes at the top of the second. The Result tab shows it, with a link to the PDF.

Every text box tells you where its text ended, so you never type a position for anything after the first element.

  • bottom is where the next element can start. textBox returns it with the lines it drew: the bottom of the last line that draws something. Rust has TextLayout::bottom(), and TextRun::bottom() for a single run of text.
  • Empty text has no bottom. The notes here are optional. When they’re empty, bottom is undefined (None in Rust), below keeps y where it was, and the photo moves up with no gap left behind.
  • A longer summary moves everything after it. When the summary wraps onto one more line, the notes, the photo and the body each move down by one line height, and none of the code changes.
  • The photo is placed by your own rectangle. An image reports nothing back, so the code adds the photo’s height and the gap to y itself.
  • The rule under the title is a decoration. It’s drawn half a gap above the summary and leaves y alone. It’s stroked rather than filled: a fill colour stays set and would colour the text drawn after it.

The report treats overflow two ways, and you choose which for each element.

The title, summary and notes must fit on the first page. They’re drawn with overflow: "error" (Overflow::Error in Rust), so text that doesn’t fit throws text-overflow instead of disappearing. The photo must fit too: when it would cross the bottom margin, the code stops with an error of its own.

The body may run on. Its box reaches the bottom margin and clips what doesn’t fit. Then overflow holds the offset of the first character it didn’t draw: a UTF-16 offset in TypeScript, a byte offset in Rust. The loop starts a new page and draws the rest from the top margin. Test overflow with !== undefined, because 0 means not even one line fitted. If no line fits even on a fresh page, a line is taller than the page, so the loop stops with an error instead of adding pages for ever.

bottom is a typographic measurement in points: the descent of the last drawn line’s font, below its baseline. A glyph that reaches lower, or a thick stroke around the text, can paint past it.

Like every position, bottom is in page space, measured from the top of the page. It’s measured before the surface’s transform, so inside transform it stays in the coordinates you drew in.

In TypeScript you pass a box as a tuple, [x, y, width, height]. The lines a text box returns describe their rect as an object with x, y, width and height.

Page breaks stay your decision: the code here makes each one from overflow. The builder’s surface doesn’t paginate, float an image beside text, or lay out tables. Pages that flow paginates for you, in both languages: headings kept with their text, running headers and “Page X of Y” footers.

  • Paragraphs a gap apart: draw each paragraph in its own text box and start the next one at bottom plus the gap, as the summary and notes do.
  • A line height for the body: pass lineHeight (with_line_height in Rust); bottom follows it.
  • Two columns: keep a y for each column, and when the left column fills, carry on at the top margin of the right one.

Next: the PDF/UA report, a report that screen readers can follow.

You’ll make four A5 pages joined by links to a website and between pages, an outline (the bookmarks panel) and page numbers that read i, ii, 1, 2. Start from it for a manual, a report or any document longer than a page or two.

The function draws the four pages, links them and returns the PDF’s bytes. It draws text, so in TypeScript it needs the text module, init({ text: true }). Both languages write the same bytes:

Page 1 of links_and_outlines.pdf
Open links_and_outlines.pdf (4 pages, 3 KB)

The result is four A5 pages with an outline and page labels. The Result tab shows it, with a link to the PDF.

  • s.link(rect, target, contents) puts a clickable box over each label on the title page. A target is a web address (uri), a page by its index from 0, or a named destination. See Pages and coordinates.
  • destination("chapter-2", 3) names the fourth page, so a link or an outline entry can go there by name. When the builder finishes, a missing page fails with page-index-out-of-range and a missing name with unknown-destination.
  • On the other pages, the link option of text (.link(…) on the run in Rust) makes the blue run itself the link, with no box to work out.
  • contents describes a link in words, for viewers and screen readers. Accessible PDFs need one on every link.
  • outline builds the bookmarks. “Chapters” has no target, so it’s a heading, shown open and in bold with both chapters inside it.
  • pageLabels numbers the pages i and ii, then 1 and 2 from the third page. pageMode: "outlines" asks the viewer to open the file with the outline showing.
  • Where a page link lands: add a fit to the target, such as fit: { type: "width" } (Fit::Width in Rust) to fill the window with the page’s width. destination takes one too.
  • The page numbers: a label also takes a prefix and a first number, so { start: 2, style: "decimal", prefix: "A-" } numbers the chapters A-1 and A-2.
  • The panel on open: pageMode also takes "thumbnails", "attachments" or "none".
  • A title and an author: add metadata({ title, author }), and displayDocTitle: true in the viewer preferences so viewers show the title instead of the file name. See Links, outlines and metadata.

Next: generate, then edit, which opens a PDF you made and changes its metadata.

Generate, then edit

You’ll generate a one-page draft report, then open its bytes, retitle it and save the edit as a revision after them. You need this whenever your app changes a PDF it already has, such as a file a user uploads or one it wrote earlier.

One function builds and saves the draft. Another opens those bytes, changes the title and author, and saves again. In TypeScript the draft needs the text module, init({ text: true }). Both languages write the same bytes:

packages/sdk/examples/generate-then-edit.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" });
}

The result is the draft’s bytes, unchanged, followed by one revision that retitles it “Final report” and names Ada Lovelace as its author. The Result tab shows it, with a link to the PDF.

  • A new document has no original bytes to append to, so the draft’s save is a full rewrite.
  • Document.open (Document::open_bytes in Rust) reads the draft. Your edits sit beside its bytes and never change them; see How Lamina PDF thinks about a PDF.
  • setMetadata changes the title, authors and other facts a viewer shows in a file’s properties. transact applies it as one transaction, which undo reverts as a whole. In Rust, apply takes the list of ops as one transaction.
  • mode: "incremental" (SaveMode::Incremental) asks for an incremental save: the draft’s bytes first, then one revision with the edit.
  • editedAt is the modification date to record, a PDF date such as D:20261030120000Z. Leave it out and no date is written, because Lamina PDF never reads the clock.
  • The builder wrote the draft’s title twice: in its Info dictionary and in its XMP metadata, an XML copy of the same facts. setMetadata changes both, so they agree.
  • More edits in the same revision: add them inside the callback, such as tx.rotatePage(doc.page(0).id, 90) (RotatePage in Rust). See Edit a PDF.
  • Removing an entry: pass null for it, as in { subject: null } (.subject(None) in Rust).
  • Your own file: open its bytes in place of the draft’s. A signed, repaired or encrypted file limits how it saves; Save a PDF lists the cases.
  • A whole new file: pass mode: "fullRewrite" (SaveMode::FullRewrite), or leave mode out and let the save choose. See Choose a save mode.
  • Edits stored as JSON: replay a saved log with doc.applyLog({ v: 1, ops }) (apply_log in Rust), as Edit a PDF shows.

Next: edit the metadata, which checks the save first and stamps when it happened.

Edit the metadata

You’ll change a PDF’s title and authors, remove its keywords, and save the edit with the time it was made. You need this for a properties dialog, a batch that fixes titles, or a pipeline that marks reports final.

A PDF keeps these facts twice: in its Info dictionary, which older viewers read, and in its XMP metadata, an XML copy that archives and search engines read. Each edit writes both from one value:

packages/sdk/examples/edit-metadata.ts
// Edit a document's title, authors and keywords, keeping its Info dictionary and XMP metadata in step.
// One edit sets the title and the authors, another removes the keywords, and the save stamps the
// time it happened. Before saving, the plan says whether the save is allowed (a certified file
// forbids metadata changes) and which PDF/A or PDF/UA claims the edit breaks.
import { Document } from "@laminapdf/sdk";
/**
* The document with its metadata edited, saved incrementally.
*
* @param savedAt - the time of the save, as a PDF date (`D:20261110093000Z`) your app takes
* from its clock.
*/
export function editMetadata(bytes: Uint8Array, savedAt: string): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
doc.setMetadata({ title: "Quarterly figures", authors: ["Ada Lovelace", "Charles Babbage"] }, { at: savedAt });
doc.removeMetadata(["keywords"]);
const options = { mode: "incremental", metadataDate: savedAt } as const;
const plan = doc.plan(options);
if (plan.refusal !== undefined) {
throw new Error(`the save would be refused: ${plan.refusal}`);
}
for (const warning of plan.conformanceWarnings) {
console.warn(`warning: ${warning.code}`);
}
return doc.save(options);
}
Page 1 of edit_metadata.pdf
Open edit_metadata.pdf (1 page, 7 KB)

The result is the original bytes, unchanged, followed by one revision. Both copies of the metadata name “Quarterly figures” and its two authors, neither holds keywords, and the modification date is the time of the save.

  • metadata() reads both copies at once. When they disagree, it trusts the XMP copy in a PDF 2.0 or PDF/A file and otherwise the copy changed last, and it lists the fields that differ in disagreements.
  • setMetadata (SetMetadata in Rust) takes a patch: a value sets a field, null removes it, and a field you leave out stays as it was. Authors are a list. The Info dictionary holds them as one string, joined with ; .
  • at is the modification date the edit records, a PDF date such as D:20261110093000Z that your app takes from its clock. Leave it out and the edit writes no date.
  • removeMetadata (RemoveMetadata) removes fields from both copies and leaves the rest of the XMP metadata as it was.
  • plan(options) says how the save will go before it happens. On a certified file, refusal is would-invalidate-signatures, because a certification allows no metadata change. conformanceWarnings lists the PDF/A or PDF/UA rules the edit breaks, such as a title removed from an accessible file. The warnings never stop a save.
  • metadataDate (with_metadata_date) is the time of the save, from your app’s clock. The save writes it as the modification date in both copies and gives the XMP metadata a new instance ID. Lamina PDF never reads the clock, so a save given neither metadataDate nor instanceId stamps nothing.
  • Only some fields: leave the others out of the patch.
  • A PDF 2.0 file: nothing. Lamina PDF writes only the two dates to its Info dictionary, which PDF 2.0 deprecates, and everything else to the XMP metadata.
  • XMP metadata that can’t be read: the edit refuses with malformed-xmp. Pass replaceMalformed: true to replace it with a new copy.
  • Removing values for good: an incremental save keeps the old values in the file’s earlier revisions. Save with mode: "fullRewrite" to drop them; the edit’s stillInEarlierRevisions says when it matters.
  • Your own instance ID: pass instanceId (with_instance_id), a UUID, to the save.

Next: save a PDF, for what a signed or repaired file allows.

Choose how a PDF opens

You’ll make a PDF open on a chosen page at the page’s width, with its bookmarks panel showing and its title in the window. You need this for a report that opens on its summary, or a manual that shows its contents first.

A PDF keeps these choices in its catalog, and every reader that follows the PDF standard reads them when it opens the file. One edit sets them:

packages/sdk/examples/set-initial-view.ts
// Choose how a PDF opens: on a given page at the page's width, with its bookmarks shown and its title in the window.
// The edit changes only what the file asks a reader to do when it opens it. A file whose open
// action runs a script keeps that action: the edit leaves the opening page alone and changes the
// rest.
import { Document, type InitialViewPatch } from "@laminapdf/sdk";
/**
* The document set to open on page `index` (0-based) at the page's width, with the bookmarks
* panel and the document's title in the window, saved incrementally. Needs
* `init({ extract: true })`.
*/
export function openOn(bytes: Uint8Array, index: number): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const view: InitialViewPatch = { pageMode: "outlines", preferences: { displayDocTitle: true } };
// An open action that runs a script or another action is never replaced, so leave the page out.
const open = doc.initialView().open;
if (open.kind === "action") {
console.warn(`the file runs a ${open.action} action when it opens; keeping it`);
} else {
view.open = { page: doc.page(index).id, zoom: "fitWidth" };
}
doc.setInitialView(view);
return doc.save({ mode: "incremental" });
}

The result is the original bytes, unchanged, followed by one revision. The file opens on the page you chose, fitted to the window’s width, with the bookmarks panel open and the document’s title in the window’s title bar.

  • initialView() reads how the file asks to open. Its open is "default" when the file leaves the first page and zoom to the reader, "page" with a target in page space, or "action" when the file runs an action, such as a script, instead.
  • setInitialView (SetInitialView in Rust) takes a patch: a value sets a field, null removes it, and a field you leave out stays as the file has it.
  • open names the page by its ID and a zoom: "fitWidth", "fitPage", "default" (the reader’s own zoom) or a percentage from 1 to 6400.
  • pageMode is the panel beside the page: "outlines" for bookmarks, "thumbnails", "attachments", "optionalContent" for layers, "fullScreen" or "none".
  • preferences holds the window’s requests, such as displayDocTitle for the title in the title bar. true sets one; false removes it, which is its default.
  • An open action that runs anything besides opening a page (a script, a named action, a page change followed by further actions) is never replaced: an edit that names the page fails with open-action-not-destination. The example reads the file’s view first and leaves the page out of its edit then. Lamina PDF never runs the action.
  • When a value needs a newer PDF version than the file declares, such as the attachments panel (PDF 1.6), the edit raises the file’s version to it.
  • Another page layout: add pageLayout, such as "twoPageRight" for two pages side by side with the cover alone.
  • The reader’s defaults again: pass null for each field you set, open included.
  • The article threads: threads() lists a file’s article threads, each with its parts as rectangles in page space, in reading order.

Next: save a PDF, for what a signed or repaired file allows.

Edit the bookmarks

You’ll add a bookmark to the top of an outline, move another under a chapter, name places links jump to, and rename one with its uses. You need this for a bookmark panel, a script that fixes a converter’s outlines, or a pipeline that adds a summary to every report.

A bookmark goes to a page and a view of it. Viewers report where they are in page space: points from the page’s top-left corner, as the rest of Lamina PDF’s API uses them. destinationAt turns that place into the destination the file stores, in the page’s user space. The example adds a bold “Summary” bookmark at the top, moves “Website” under “Chapters”, names the last page summary and renames chapter-2 to methods:

packages/sdk/examples/edit-bookmarks.ts
// Edit a document's bookmarks and named destinations: add a bookmark, move one, and name a place links can jump to.
// A new "Summary" bookmark goes first, in bold, showing the top of the last page. The place comes
// from page space, as a viewer reports it, and becomes the destination the bookmark stores. The
// same place gets the name `summary`, the destination `chapter-2` is renamed with every bookmark
// that uses it, and the "Website" bookmark moves to the end of the "Chapters" bookmark, when the
// file has them.
import { Document } from "@laminapdf/sdk";
/** The document with its bookmarks edited, saved incrementally. Needs `init({ extract: true })`. */
export function editBookmarks(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
// The top of the last page, in page space (points from the page's top-left).
const last = Math.max(doc.pageCount - 1, 0);
const summary = doc.destinationAt(last, { kind: "at", x: 0, y: 0 });
doc.apply([
{
op: "addOutlineItem",
args: {
parent: null,
at: "first",
title: "Summary",
target: { destination: summary },
style: { bold: true },
},
},
{ op: "setNamedDestination", args: { name: "summary", destination: summary } },
]);
// Rename a destination, if the file has it: bookmarks and links that use it follow.
if (doc.namedDestinations().some((d) => d.name === "chapter-2")) {
doc.apply([{ op: "renameNamedDestination", args: { from: "chapter-2", to: "methods" } }]);
}
const outline = doc.outline();
const find = (title: string) => outline.find((node) => node.title === title)?.id;
const website = find("Website");
const chapters = find("Chapters");
if (website !== undefined && chapters !== undefined) {
doc.apply([{ op: "moveOutlineItem", args: { item: website, parent: chapters, at: "last" } }]);
}
return doc.save({ mode: "incremental" });
}
Page 1 of edit_bookmarks.pdf
Open edit_bookmarks.pdf (4 pages, 7 KB)

The result is the original bytes, unchanged, followed by one revision. Its outline starts with “Summary” in bold, the “Website” bookmark sits at the end of “Chapters”, and the name summary goes to the top of the last page. The bookmark that went to chapter-2 now goes to methods, the same place under its new name.

  • outline() lists every bookmark with its id, which the bookmark edits take, its title, where it goes, its colour and style, and whether its children show.
  • addOutlineItem (AddOutlineItem in Rust) adds a bookmark under a parent (null for the top level) at a position: "first", "last", { before: id } or { after: id }. Its target is a page ({ destination }), a named destination ({ named }) or a web address ({ uri }). The edit’s result lists the new bookmark’s ID in createdOutlineItems.
  • updateOutlineItem, moveOutlineItem and deleteOutlineItem change, move and delete a bookmark by its ID. A moved bookmark takes its children with it and keeps its ID. A deleted one takes its children with it, or leaves them in its place with children: "promote".
  • setNamedDestination gives a place a name, or points an existing name elsewhere. renameNamedDestination renames it, together with every bookmark, link and opening view of the file that uses it. Pass links: "keep" to leave those alone.
  • Lamina PDF keeps each bookmark’s place in the tree, and the counts of open bookmarks, consistent after every edit. When a file’s outline was broken, such as a loop or a wrong last item, the first edit rewrites it whole and says so in outlineRepaired.
  • A colour or style: pass style: { color: "#c00000", bold: true, italic: false }. Leave color out for the viewer’s default black.
  • A web address: pass target: { uri: "https://example.com" }. Only absolute http, https and mailto addresses are allowed; anything else, javascript: first, fails with link-uri-refused.
  • The current view: pass what your viewer shows to destinationAt, such as { kind: "at", x, y, zoom } for a point at the top-left, or { kind: "fit-width", y } to fit the width.
  • Deleting a name: deleteNamedDestination leaves the bookmarks and links that use it alone, since removing them could lose your content. The edit’s destinationUses lists them, so you can retarget or delete them next.
  • A signed file: a bookmark edit changes the document’s structure, so a certified file refuses the save. On a file with approval signatures only, the save appends a revision and the signatures stay valid.

Next: save a PDF, for what a signed or repaired file allows.

Add a contents page

You’ll add a contents page to the front of a PDF, made from its bookmarks. Each entry shows its page’s label and opens that page when clicked. You need this for a long report or a merged file that has bookmarks but no contents page to print.

The page is made from the bookmarks only: Lamina PDF never guesses headings from the text. One edit lays it out, inserts it and links its entries:

packages/sdk/examples/create-contents-page.ts
// Add a clickable contents page to a PDF, made from its bookmarks.
// The page lists the bookmarks that go to a page, two levels deep, each with the label its page
// shows and a link to it, and gets a bookmark of its own. It's one edit, so one undo takes it out
// again, and it saves incrementally.
import { Document, Font } from "@laminapdf/sdk";
/**
* The document with a contents page before the first page, set in the font `font` (embedded, so
* a PDF/A or PDF/UA-1 file keeps its claim), saved incrementally. Needs `init({ text: true })`.
*/
export function addContents(bytes: Uint8Array, font: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
doc.createContentsPage({ font: Font.fromBytes(font), bookmark: true });
return doc.save({ mode: "incremental" });
}

The result is the original bytes, unchanged, followed by one revision. The new first page lists the bookmarks under a “Contents” heading, and a “Contents” bookmark at the top of the outline opens it.

  • The page lists each bookmark that goes to a page, two levels deep. A bookmark that opens a web address, or goes nowhere, is left out, but the bookmarks inside it are still listed.
  • Each entry ends with the label its page shows once the contents page is in. Say a file numbers its front matter i, ii and its body 1, 2. A contents page at the front joins the front matter as “i”, so the old “i” and “ii” print as “ii” and “iii”, and the body keeps 1 and 2. In a file without labels, the numbers move up by one for each contents page.
  • The entries are links to the bookmarks’ places, and each link’s description is the bookmark’s title, which screen readers read.
  • In a tagged file, the page is tagged too: a TOC element with a TOCI for each entry joins the document’s structure tree.
  • The font is embedded and subset. Without one, the page is set in Helvetica, which isn’t embedded, so a file that claims PDF/A or PDF/UA-1 refuses it with font-not-embedded. A file with no bookmark that goes to a page fails with no-bookmarks.
  • It’s one edit: one undo removes the page, its links and its bookmark.
  • One level: pass levels: 1 (with_levels(1) in Rust) to list only the top-level bookmarks.
  • Another place: pass at: "end", or { after: id } with a page’s ID (with_at in Rust).
  • Another heading: pass title (with_title), in the document’s own language.
  • Text size: pass size (with_size), from 4 to 72 points; entries are 11 points by default, and the heading half again as large. A contents page longer than ten pages fails with invalid-op: list one level, or use a smaller size.
  • Characters the font lacks: add fallbacks (with_fallback), fonts tried in order. A title no font can draw fails with missing-glyph.

Next: edit the bookmarks the page is made from.

You’ll add two links to a report’s first page: one on a box over its chart, one on a line of text. You need this for a link tool in an editor, or a script that links every product name in a catalogue to its web page.

Viewers report a drawn box or a text selection in page space: points from the page’s top-left corner. linkOnArea and linkOnText turn those boxes into the edit that adds the link, in the page’s user space. The example links the chart and the line “Widgets sold out in May.” to two web pages, then changes the chart link’s address:

Page 1 of add_links.pdf
Open add_links.pdf (2 pages, 25 KB)

The result is the original bytes, unchanged, followed by two revisions. Neither link draws a border, so the page looks the same, but a click on the chart opens the 2026 sales page and a click on the line opens the widgets page.

  • linkOnArea takes one box, and linkOnText takes one box per line of the selected text. A link on text follows only its lines, so the gaps between them stay plain text.
  • The report is a tagged PDF, the kind screen readers follow. In a tagged file, linkOnText also finds the words under the boxes, and the new link joins the document’s structure around them.
  • Each link takes a target: a page ({ destination }), a named destination ({ named }) or a web address ({ uri }), as a bookmark does.
  • contents is the link’s description, which screen readers read out. The accessible PDF standard, PDF/UA, asks every link for one.
  • The edit’s result lists each new link’s ID in createdAnnotations. updateLink takes that ID to change a link’s boxes, target or description, and deleteLink removes it. pageLinks lists the IDs of the links a page already has.
  • A page of the file: pass { destination: doc.destinationAt(page, view) } as the target, with the view your reader shows.
  • An email address: pass { uri: "mailto:sales@example.com" }. Only absolute http, https and mailto addresses are allowed. Any other address, such as a javascript: one, fails with link-uri-refused.
  • Several lines: pass every line’s box to linkOnText, each [x0, y0, x1, y1], in reading order.
  • A file that claims PDF/UA but isn’t tagged: the edit fails with link-not-tagged, since an untagged link would break the claim.
  • A signed file: you can add links to a certified file that allows comments, or to one with only approval signatures. Lamina PDF appends them as a new revision, and the signatures stay valid. A certification that forbids comments makes the save fail.

Next: edit the bookmarks, which go to places in the same way.

Mark up a page

You’ll mark up a report’s first page the way a reviewer does: highlight a line, leave a note beside the chart, and propose a better word. You need this for a review tool in an editor, or a script that flags every sentence a checker finds.

Viewers report a text selection as one box per line, and a click as a point, in page space: points from the page’s top-left corner. markText, noteAt and caretAt turn those into the edit that adds the mark, in the page’s user space. replaceText adds a strike-out and a caret together:

packages/sdk/examples/mark-up.ts
// Mark up a page: highlight a line of text, leave a note beside the chart, and propose a better word.
// The boxes are in page space (points from the page's top-left), as a viewer reports a text
// selection and a click. Each mark records who made it and when. In a tagged document a
// highlight's description, which screen readers read, is the text it marks.
import { Document } from "@laminapdf/sdk";
// Where the marks go on the example's input, the quarterly report, in points from the page's
// top-left: for your own file, take them from your viewer's selection and clicks.
/** The line "Widgets sold out in May.", as a selection gives it: `[x0, y0, x1, y1]`. */
const WIDGETS_LINE = [56, 358.241, 196.335, 373.223] as const;
/** The words "sold out" on that line. */
const SOLD_OUT = [114.902, 358.241, 156.713, 373.223] as const;
/** The note's spot, right of the chart. */
const BESIDE_CHART = [310, 140] as const;
/** The colour of a paper sticky note. */
const STICKY_YELLOW: [number, number, number] = [1, 0.82, 0];
/**
* The document with a highlight, a note and a proposed word on its first page, saved
* incrementally. `at` is when the marks were made, as a PDF date. Needs `init({ extract: true })`.
*/
export function markUp(bytes: Uint8Array, at: string): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const byMe = { author: "Ada Lovelace", created: at, modified: at };
// In a tagged document the highlight's description is already the marked text; add who made it.
const highlight = doc.markText(0, "highlight", [WIDGETS_LINE]);
highlight.common = { ...highlight.common, ...byMe };
const note = doc.noteAt(0, BESIDE_CHART, "Add June's figures?", "comment");
note.common = { ...note.common, ...byMe, color: STICKY_YELLOW };
doc.apply([
{ op: "addAnnot", args: highlight },
{ op: "addAnnot", args: note },
]);
// "sold out" reads better as "ran out": a strike-out and a caret, applied as one undo step.
doc.replaceText(0, [SOLD_OUT], "ran out", byMe);
return doc.save({ mode: "incremental" });
}
Page 1 of mark_up.pdf
Open mark_up.pdf (2 pages, 28 KB)

The result is the original bytes, unchanged, followed by two revisions. “Widgets sold out in May.” is highlighted in yellow, a speech-bubble note sits right of the chart, and “sold out” is struck through with a caret after it that holds “ran out”.

  • markText takes one box per line of the selected text and a kind: highlight, underline, strikeOut or squiggly. Each box becomes one of the mark’s quadrilaterals, so a mark over three lines covers only those lines.
  • Lamina PDF draws every mark itself and stores the drawing in the file, so every reader that draws stored appearances, as pdf.js, PDFium and Acrobat do, shows the same mark. A highlight multiplies its colour with the page, which keeps the text under it legible.
  • The report is a tagged PDF, the kind screen readers follow. In a tagged file, a mark’s description (contents) is the text it marks, or the kind of mark when its boxes hold no text. The mark joins the document’s structure right after that text.
  • noteAt puts a 20-point icon with its top-left corner on the point, and a pop-up beside it that shows the comment. The note keeps its size at any zoom and stays upright when the page turns, as Acrobat’s notes do.
  • replaceText groups the strike-out with a caret, so a reader shows, moves and deletes them as one correction. The caret holds the replacement text. Both edits are one step: a single undo removes both.
  • The author and dates come from your code, never from a clock inside Lamina PDF, so the same edit gives the same file wherever it runs.
  • Another mark: pass "underline", "strikeOut" or "squiggly" to markText.
  • A colour or opacity: set common.color ([r, g, b] from 0 to 1) and common.opacity before applying the edit.
  • A note’s icon: pass "note", "comment", "key", "help", "paragraph", "newParagraph" or "insert".
  • Change a mark later: updateAnnot takes the ID from createdAnnotations and a new color, opacity or spec. Lamina PDF draws the mark again. deleteAnnot removes a mark, with its pop-up and the rest of its group.
  • A PDF/A or PDF/UA file: the marks keep the file’s claims, and doc.plan() warns before you save when an edit breaks one. A highlight breaks PDF/A-1, which forbids transparency (pdfa-transparency). A mark with an empty description breaks PDF/UA (annot-without-contents).
  • A signed file: you can mark up a certified file that allows comments, or one with only approval signatures. Lamina PDF appends the marks as a new revision, and the signatures stay valid.

Next: add links, another kind of annotation made the same way.

Answer a review

You’ll answer the review left on a report: reply to the note asking a question, and mark the highlighted line as done. You need this for a review tool that lists a document’s comments, or a script that closes every comment a checker has handled.

commentThreads gives each comment as a thread: the comment, its replies in order, the status set on it and, for a highlight, the text it marks. The addReply and setReviewState edits answer a comment and set its status. Here they answer the comments left by Mark up a page:

packages/sdk/examples/review-comments.ts
// Answer a review: read the comments on a marked-up report, reply to a question and mark a
// highlight done.
// The comments come back as threads, each with its replies and the status set on it, and a
// highlight's thread carries the text it marks. A reply and a status are annotations of their
// own, so the review keeps its history.
import { Document, type Op } from "@laminapdf/sdk";
/** Who answers the review. */
const ME = "Grace Hopper";
/**
* The document with a reply to every note that asks a question, and every highlight marked
* done, saved incrementally. `at` is when the review was answered, as a PDF date. Needs
* `init({ extract: true })`.
*/
export function reviewComments(bytes: Uint8Array, at: string): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const ops: Op[] = [];
for (const thread of doc.commentThreads()) {
const { id, subtype, contents } = thread.comment;
if (subtype === "Text" && contents?.endsWith("?")) {
const reply = { parent: id, contents: "June's figures are in the appendix.", author: ME, created: at };
ops.push({ op: "addReply", args: reply });
} else if (subtype === "Highlight" && thread.review !== "Completed") {
// `quoted` is the text the highlight marks, for a list of what was checked.
ops.push({ op: "setReviewState", args: { target: id, state: "completed", author: ME, created: at } });
}
}
// Every answer is one undo step.
doc.apply(ops);
return doc.save({ mode: "incremental" });
}
Page 1 of review_comments.pdf
Open review_comments.pdf (2 pages, 31 KB)

The page looks the same as before: a reply and a status draw nothing on the page. Open the result in a reader with a comments panel, such as Acrobat, and the note has a reply from Grace Hopper, and the highlight is marked Completed.

  • A reply and a status are annotations of their own, each pointing at the comment it answers, as ISO 32000-2 describes and Acrobat writes them. Changing a status adds a new one rather than replacing the old, so the file keeps the review’s history. A thread’s review is its latest Review status, by date.
  • Each reply and status sits over its comment and draws nothing, so no reader shows a second icon on the page. It still prints, which keeps a PDF/A file valid.
  • A thread can hold replies to replies, and a reply on another page than its comment. Each part says which page it is on.
  • quoted is the text under a highlight, underline or strike-out, read from the page. It needs the extract or text module.
  • Some apps leave a reply to a comment that’s gone, or replies that answer each other in a ring. Each comes back as a thread of its own marked broken, so nothing is lost.
  • The author and dates come from your code, never from a clock inside Lamina PDF, so the same edit gives the same file wherever it runs.
  • Another status: "accepted", "rejected", "cancelled", "completed" or "none" set the review status. "marked" and "unmarked" set a reviewer’s check mark, which a thread gives as marked.
  • Some pages only: pass page indexes, doc.commentThreads([0, 1]), for the threads whose comments are on those pages.
  • Delete comments: doc.deleteAnnotations(ids) deletes a selection in one undo step, each comment with its replies, statuses and pop-up. Select a comment and one of its replies, and both go.
  • Edit a reply: updateAnnot changes a reply’s text like any other annotation’s.
  • A signed file: you can answer a review on a certified file that allows comments, or one with only approval signatures. Lamina PDF appends the answers as a new revision, and the signatures stay valid.

Next: add links, another annotation you can add to a page.

Exchange comments with other apps

You’ll send a report’s comments to a reviewer who uses another PDF app, and bring their answers back into your copy. You need this when people review the same document in different apps, or when the comments should travel without the PDF.

exportAnnotations writes the comments as XFDF, the format Acrobat and most PDF apps import. importAnnotations reads the XFDF or FDF file the reviewer sends back and adds its comments to the document as one change:

packages/sdk/examples/exchange-comments.ts
// Send a PDF's comments to a reviewer who uses another app, and bring their comments back:
// export them as XFDF, which Acrobat and most PDF apps import, and import the XFDF file they
// send back. The import keeps the comments already in the file and adds the new ones, with
// their replies and statuses, as one change that a single undo takes back.
import { Document } from "@laminapdf/sdk";
/**
* The document's comments as XFDF, recording the file's name so an import can tell when it is
* given to another PDF. Needs `init({ extract: true })`.
*/
export function exportComments(bytes: Uint8Array, name: string): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
return doc.exportAnnotations({ format: "xfdf", file: name });
}
/** The document with a reviewer's XFDF or FDF comments added to its own. */
export function importComments(bytes: Uint8Array, xfdf: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const { summary } = doc.importAnnotations(xfdf, { mode: "merge" });
console.log(`${summary.added} comments added, ${summary.matched} already here`);
// A sound, a form field's value or a comment for a missing page is left out, and said.
for (const warning of summary.warnings) {
console.warn(warning.code, warning.kind ?? "", warning.reason ?? "");
}
return doc.save();
}

The comments already in your copy stay as they are. The reviewer’s new comments, replies and statuses join them, each drawn the way Lamina PDF draws its own, and one undo takes them all back.

  • XFDF and FDF keep every reply with the comment it answers, carry attached files, and record which PDF they were made for. Importing a file made for another PDF still works, but the summary warns with interchange-document-mismatch: its comments may land in the wrong places. The check compares the two PDFs’ identifiers, or, when either has none, the file name you pass as file.
  • The import matches comments by their name (/NM) on the same page. By default, a comment the file names that is already in your copy is kept as it is, and the file’s other comments are added.
  • What Lamina PDF can’t make is left out and listed in summary.warnings as interchange-skipped: a sound comment, a link, a form field’s value, or a comment for a page your copy doesn’t have.
  • A file that doesn’t read fails with interchange-malformed, which names the line where reading stopped. An XFDF file that declares a DTD is refused with interchange-dtd, since a DTD can define entities that expand without end or read other files.
  • See what an import will do first: previewImport gives the same summary without changing anything: how many comments it adds and on which pages, and what it leaves out.
  • Replace the comments the file names: pass { mode: "replace" }, and each one already in your copy is deleted, with its replies, and the file’s version added.
  • Keep both: pass { mode: "add" }, and the file’s comments are added as copies.
  • Notes for a notes app: export { format: "markdown", comments: "highlightsAndNotes" }. Each page gets a heading, and each highlight’s text is quoted under it.
  • FDF instead of XFDF: export { format: "fdf" }, for apps that only read FDF.

Next: answer a review to reply to the comments you brought back.

Fill a form from JSON

You’ll fill an invoice form with answers that come from your own system, such as an order database, without anyone typing them in. You need this when the same form is filled many times with different data, or when answers move between apps.

fillForm takes the answers as a JSON object, { fields: { "<field name>": value } }, and fills the form in one change. The form’s own calculations then work out each line’s amount and the invoice’s total:

packages/sdk/examples/fill-form-from-json.ts
// Fill an invoice form from JSON: the answers come from an order system, go into the form as one
// change, and the form's own calculations work out each line's amount and the total.
//
// The answers are `{ fields: { "<field name>": value } }`. Fields are matched by their full names
// (`customer.name` is `name` inside `customer`). A check box takes `true` or `false`, a list an
// array of its options. Names the form doesn't have, fields a signature locks and values a field
// refuses are listed; every other answer is filled.
import { Document, type FormDataJson } from "@laminapdf/sdk";
/** The invoice form filled from `answers`, saved after the original bytes. Needs `init({ extract: true })`. */
export function fillInvoice(form: Uint8Array, answers: FormDataJson): Uint8Array<ArrayBuffer> {
using doc = Document.open(form);
const { unknown, refused } = doc.fillForm(answers);
for (const name of unknown) console.warn(`no field named ${name}`);
for (const field of refused) console.warn(`${field.name} refused its value (${field.code})`);
const total = doc.formFields().fields.find((f) => f.name === "total")?.value;
console.log("total:", total);
return doc.save({ mode: "incremental" });
}

Each answer is drawn into its field the way the form formats it, so a price of 1200 shows as $1,200.00. One undo takes every answer back.

  • Fields are matched by their full names. A field inside another is named after both, joined by a full stop: customer.name is the name field inside customer. formFields() lists every field with its full name.
  • Each kind of field takes its own kind of value. A text field takes a string. A check box with one way to be ticked takes true or false, and radio buttons take the name or export value of the choice to turn on. A list takes an array of its options. null empties any field.
  • What can’t be filled is listed, and the rest is filled. A name the form doesn’t have is listed in unknown. A field a signature locks is listed in locked and left as it is. A value its field refuses is listed in refused with a code: field-value-invalid for text longer than the field allows or an option the list doesn’t have, field-is-signature for a signature field.
  • Calculations run once, after the last answer. A total sees every answer before it is worked out. Pass { calculate: false } to leave the form’s totals as they are.
  • Exports use the same object. exportFormData("json") writes it, so an export fills a copy of the form exactly as it was. Its schema is docs/schemas/form-data.schema.json in the @laminapdf/sdk package.
  • Fill from a file another app wrote: importFormData(bytes) reads XFDF and FDF as well as JSON, telling them apart by their first bytes. An XFDF file that declares a DTD is refused with interchange-dtd.
  • Save the answers for another app: exportFormData("xfdf") or exportFormData("fdf") writes them in the formats Acrobat and most PDF apps import.
  • Start again: resetFields() gives every field its default value, or empties it, as a form’s Reset button does. Pass the IDs formFields() gives to reset only those fields.
  • Forms with an XFA part: some forms made in Adobe’s tools carry a second, XFA version of their fields. fillForm’s result then has xfaNotUpdated: true, because Adobe’s apps keep showing the XFA version’s old answers. Check the filled form in a PDF app other than Adobe’s, or ask the sender for a form without the XFA version.

Next: flatten the filled form so its answers can’t be changed.

Flatten a filled form

You’ll flatten a filled invoice form: its answers become part of the page, like its printed labels. You need this before you send a filled form to someone who should read the answers but not change them, or to an archive that keeps no form fields.

flattenForm takes the fields to flatten, or, when you leave them out, every field that isn’t a signature or locked by one, and whether the copy is for the screen or for printing. Lamina PDF draws each field’s picture (its appearance) into the page, answer included, and removes the field from the form. Here it fills the invoice from Fill a form from JSON, then flattens it for printing:

packages/sdk/examples/flatten-form.ts
// Flatten a filled invoice form for sending: every answer becomes part of its page, so the copy
// shows the same everywhere and the answers can no longer be changed.
// The fields go from the form; signature fields, and fields a signature locks, stay. Saving
// as a full rewrite leaves no earlier revision that still holds the fields.
import { Document, type FormDataJson } from "@laminapdf/sdk";
/**
* The form filled from `answers`, then every field drawn into its page, as a printer would show
* it. Needs `init({ extract: true })`.
*/
export function flattenForm(form: Uint8Array, answers: FormDataJson): Uint8Array<ArrayBuffer> {
using doc = Document.open(form);
doc.fillForm(answers);
const edited = doc.flattenForm(undefined, "print");
// A push button or radio button with no appearance of its own stays.
for (const warning of edited.warnings ?? []) {
console.warn(warning.code);
}
// A full rewrite keeps only the flattened pages, not the revisions with the fields.
return doc.save({ mode: "fullRewrite" });
}
Page 1 of flatten_form.pdf
Open flatten_form.pdf (1 page, 6 KB)

The page looks the same as the filled form. Click a box in a PDF reader, and nothing happens: the answers are now part of the page.

  • Each field keeps the picture a reader shows for it. Flattening draws that picture at the same place and size, then removes the field. Lamina PDF first draws a picture with the answer for a field that has none, and for every field of a form that asks readers to draw its fields.
  • "print" keeps what a printer shows, and "view" what a screen shows. A field hidden for the copy you make is removed without being drawn.
  • Signature fields are never flattened: a signature drawn into a page would look present when nobody can check it. Naming one fails with field-is-signature. Leaving the fields out flattens every other field, except those a signature locks.
  • A push button or radio button with no picture of its own, which each reader draws its own way, stays a field, and the edit’s warnings list it as flatten-no-appearance.
  • Some forms made in Adobe’s tools carry a second, XFA version of their fields. Flattening removes it, since Adobe’s apps would otherwise show the flattened fields again. When fields other than signatures are left, the warnings say so with xfa-removed.
  • In a tagged file, the drawings are marked as decoration, outside the structure that screen readers follow, so a screen reader no longer reads the answers out. A file that claims PDF/UA-1 then gets the flatten-untagged warning when you save.
  • Saving as a full rewrite drops the old revisions. An incremental save keeps them, fields and answers included, at the end of the file.
  • Some fields only: pass their IDs, as formFields() lists them, instead of undefined. The other fields stay fillable. Naming a field a signature locks makes the save fail.
  • For the screen: pass "view", and fields that print but don’t show on screen are removed without being drawn.
  • A signed form: flattening changes what a page draws, so saving a flattened certified form fails, whatever its permissions. With only approval signatures, you can save it incrementally (mode: "auto"), not as the full rewrite this example uses. Each signature stays valid for the revision it signed, and the fields its lock covers stay fillable.

Next: flatten comments to do the same for a review’s marks.

Check for an XFA form

You’ll check a PDF form for an XFA part. XFA is an older Adobe format, deprecated in PDF 2.0, that forms made in Adobe’s LiveCycle tools may carry. You need this before you fill a form, so you know what a person will see in each app.

xfaFacts says whether the form has an XFA part and what kind it is. xfa also gives each packet’s bytes. A dynamic form has placeholder pages, usually a message asking you to wait, and only Adobe’s apps can show or fill it. A static form has real pages and ordinary fields beside its XFA part. The example leaves a dynamic form alone and removes a static form’s XFA part with the removeXfa edit:

packages/sdk/examples/check-xfa-form.ts
// Check whether a PDF form is an XFA form, and make a static one show the same answers in every
// app. An XFA form is an older Adobe format that only Adobe's apps lay out. A dynamic one has
// placeholder pages and nothing to fill here; a static one has real pages and ordinary fields,
// but Adobe's apps show the XFA part's own answers, so the part is removed.
import { Document } from "@laminapdf/sdk";
/**
* The form as it saves: without its XFA part when it is a static XFA form, unchanged otherwise.
* Needs `init({ extract: true })`.
*/
export function checkXfaForm(form: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(form);
const xfa = doc.xfaFacts();
if (xfa === undefined) {
console.warn("not an XFA form");
} else if (xfa.kind === "dynamic") {
// Only Adobe's apps lay it out: leave it as it is.
console.warn("a dynamic XFA form: open it in Adobe Acrobat");
} else {
console.warn("a static XFA form: removing its XFA part");
doc.apply([{ op: "removeXfa", args: {} }]);
}
return doc.save({ mode: "fullRewrite" });
}
Page 1 of check_xfa_form.pdf
Open check_xfa_form.pdf (1 page, 691 bytes)

The saved form has the same pages and fields, and no XFA part.

  • A form is dynamic when the catalog’s /NeedsRendering is true, when its config packet requires dynamic rendering, or when its template has fields and its form has none. Any other form with an XFA part is static.
  • Adobe’s apps show a static form’s XFA answers, not the fields’, so answers filled into the fields alone don’t show there. Removing the XFA part makes every app show the fields.
  • Some static forms keep their answers only in the XFA part, so their fields look empty once it is gone. Undo brings the part back.
  • A certified file, and a file with usage rights, don’t allow the edit: saving it would change the file after the signature.

Next: fill a form from JSON.

Flatten comments

You’ll flatten the comments on a marked-up report: its highlight, strike-out, note and drawings become part of their page. You need this before you send a reviewed copy to someone who should see the marks but not change them, or to a printer that leaves comments out.

flattenAnnotations takes the annotations to flatten and whether the copy is for the screen or for printing. Each annotation’s picture is drawn into its page where it was, and the annotation goes, with its pop-up and its replies. Here it flattens the report from Mark up a page for printing:

packages/sdk/examples/flatten-comments.ts
// Flatten a marked-up report for printing: every comment and mark becomes part of its page, so
// the copy prints and shows the same everywhere and the marks can no longer be selected, edited
// or removed as comments.
// The annotations themselves go, with their pop-ups and replies. Saving as a full rewrite leaves no earlier
// revision that still holds them.
import { Document } from "@laminapdf/sdk";
/**
* The document with every comment drawn into its page, as a printer would show it. Needs
* `init({ extract: true })`.
*/
export function flattenComments(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const edited = doc.flattenAnnotations("all", "print");
// Marks with no picture to keep, such as a file attachment, stay as they are.
for (const warning of edited.warnings ?? []) {
console.warn(warning.code);
}
// A full rewrite keeps only the flattened pages, not the revision with the comments.
return doc.save({ mode: "fullRewrite" });
}
Page 1 of flatten_comments.pdf
Open flatten_comments.pdf (2 pages, 20 KB)

The pages look the same as before. Open the result in a reader with a comments panel, and the panel is empty: the marks are now part of the page, like its text.

  • Each annotation keeps the picture a reader shows for it, its appearance. Flattening draws that picture at the same place and size, then removes the annotation, so the marks can no longer be selected, edited or removed as comments.
  • "print" keeps what a printer shows, and "view" what a screen shows. A mark meant only for the screen stays an annotation when you flatten for printing, and a hidden one always stays.
  • Some marks have no picture of their own. Lamina PDF draws one first for notes, carets, text markup, ink, shapes, lines, polygons and text boxes. A file attachment or a sound has none to keep, so it stays, and the edit’s warnings list it as flatten-no-appearance.
  • In a tagged file, the drawings are marked as decoration, outside the structure that screen readers follow, and the comments leave the structure tree. A file that claims PDF/UA-1 then gets the flatten-untagged warning when you save: the comments’ text is no longer read out.
  • Form fields are never flattened this way: naming one fails with flatten-widget. Flatten a filled form does that. A locked annotation can’t be removed, so naming one, or a comment whose reply is locked, fails with annotation-locked. "all" and { pages } leave both out, with links.
  • Saving as a full rewrite drops the old revision. An incremental save keeps it, comments included, at the end of the file.
  • Some pages only: pass { pages: [0, 2] } (0-based) instead of "all".
  • A selection: pass { annotations: ids } with IDs from pageAnnotations or commentThreads, or apply the flattenAnnots op with them, which works in every module.
  • For the screen: pass "view", and marks that print but don’t show on screen stay as they are.
  • A signed file: flattening changes what a page draws, so a certified file can’t save it, whatever its permissions. A file with only approval signatures can save it incrementally (mode: "auto"), not as the full rewrite this example asks for, which would break the signatures. Each signature stays valid for the revision it signed, and the flattened pages come after it.

Next: answer a review to reply to comments before you flatten them.

Print a comment summary

You’ll make a summary of a review: a new PDF that lists every comment, with each page drawn small beside its comments and their numbers marked on it. You need one to send a review to someone who shouldn’t have to open each comment, or to print it.

commentSummary reads the comments and lays the summary out in the font you give it. Each comment comes with its number, author, date, status, the text it marks, its note and its replies. Here it summarises the review answered in Answer a review:

packages/sdk/examples/comment-summary.ts
// Print a summary of a review: a new PDF that lists every comment, with each page drawn small
// beside its comments and their numbers marked on it.
// The summary is tagged and conforms to PDF/UA-1, so a screen reader reads it in order. The
// reviewed file doesn't change.
import { Document, Font } from "@laminapdf/sdk";
/**
* A summary of the comments on `bytes`, set in the font `font`, which the summary embeds. Needs
* `init({ text: true })`.
*/
export function summariseComments(bytes: Uint8Array, font: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
using summary = doc.commentSummary({ font: Font.fromBytes(font) });
// A page whose fonts the file doesn't embed is listed without its drawing.
for (const warning of summary.warnings) {
console.warn(warning.code);
}
return summary.save();
}
Page 1 of comment_summary.pdf
Open comment_summary.pdf (1 page, 22 KB)

The reviewed file doesn’t change. The summary is a document of its own, unsaved until you save it.

  • Comments are numbered in the order of the document: page by page, and on each page in the order the file lists them. The same numbers mark the drawn page, so a reader can match a mark to its comment.
  • Each drawn page is a copy of the page itself, not a picture of it. It stays sharp at any zoom, and its text can be selected and searched.
  • The copy shows what the page itself draws. Annotations and form fields aren’t part of it, so a filled form’s fields show blank; the numbers mark where the comments are. A layer hidden when the document opens stays hidden: what the page draws on it is left out, and drawings the page reuses from elsewhere in the file keep their layers, hidden as before.
  • The summary is tagged and conforms to PDF/UA-1, so a screen reader reads it in order. Each drawn page has a description that names the page and the comments it marks.
  • PDF/UA-1 needs every font embedded. A page set in a font the file only names, such as Helvetica, is listed without its drawing, and so is a page whose content can’t be read to its end within the document’s limits. The summary’s warnings say so with summary-page-not-drawn.
  • Replies are listed under their comment, and a reply on another page still belongs to its comment. The status is the comment’s latest review status, with “Marked” when someone checked it.
  • A list without pages: pass layout: "list" (in Rust, SummaryLayout::List), which suits a long review.
  • Some comments only: pass comments with the IDs from commentThreads, such as those a comments panel shows.
  • Less detail: pass replies: false or status: false.
  • Every page: pass emptyPages: true to list the pages without comments too, each saying it has none.
  • Paper: the summary takes the size of the document’s first page; pass paper: [595.28, 841.89] for A4, in points.
  • Title: pass title. Without one, the summary is titled “Comments on” and the document’s title.
  • Language: pass language with the language most comments are in, so screen readers read them in that language. Pass words too, so the summary’s own words are in it: words: { page: "Seite {label}", kinds: { Text: "Notiz" } } (in Rust, SummaryOptions::with_words with a SummaryWords). Each word is a template: the summary fills in the names in braces, such as {label}. Any word you leave out stays in English. Dates stay in ISO 8601.

Next: flatten comments to draw them into the pages instead.

Draw on a page

You’ll draw on a report’s first page as a reviewer does: a cloud around a row of the table, an arrow at the chart and a wavy line under the total. You need this for a drawing tool in an editor, or a script that circles what a checker finds.

Viewers report where a pointer went as points in page space: points from the page’s top-left corner. inkAt, shapeAt, lineAt and polyAt turn those points into the page’s user space and give the edit that adds the drawing:

packages/sdk/examples/draw-on-page.ts
// Draw on a page: a cloud around a row of the table, an arrow pointing at the chart, and a
// freehand underline below the total.
// The points and boxes are in page space (points from the page's top-left), as a viewer reports
// where a pointer went. Each mark records who drew it and when, and describes itself for screen
// readers.
import { type AnnotColor, type AnnotCommon, Document } from "@laminapdf/sdk";
// Where the marks go on the example's input, the quarterly report, in points from the page's
// top-left: for your own file, take them from your viewer's pointer.
/** Around the table's Q2 row: `[x0, y0, x1, y1]`. */
const Q2_ROW = [48, 317, 340, 338] as const;
/** From the empty space right of the chart to its right edge: `[x, y]` each. */
const ARROW = [
[420, 180],
[264, 200],
] as const;
/** A wavy underline below "Total sales", as a pen traced it. */
const UNDERLINE = [
[56, 482],
[72, 478],
[88, 484],
[104, 478],
[120, 484],
[136, 478],
[152, 484],
[168, 478],
[180, 482],
] as const;
/** A reviewer's red pen. */
const RED: AnnotColor = [0.85, 0.1, 0.1];
/**
* The document with a cloud, an arrow and an underline drawn on its first page, saved
* incrementally. `at` is when the marks were drawn, as a PDF date.
*/
export function drawOnPage(bytes: Uint8Array, at: string): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const byMe = (contents: string): AnnotCommon => ({
contents,
author: "Ada Lovelace",
created: at,
modified: at,
color: RED,
});
const cloud = doc.shapeAt(0, "square", Q2_ROW);
if (cloud.spec.type === "shape") cloud.spec.border = { width: 1.5, style: { type: "cloudy", intensity: 0.5 } };
cloud.common = byMe("Check the Q2 figures");
const [from, to] = ARROW;
const arrow = doc.lineAt(0, from, to, ["none", "closedArrow"]);
if (arrow.spec.type === "line") {
arrow.spec.border = { width: 2, style: { type: "solid" } };
arrow.spec.interior = RED;
}
arrow.common = byMe("Label the chart's axes");
const underline = doc.inkAt(0, [UNDERLINE], 1.5);
underline.common = byMe("Underlined: the total");
doc.apply([
{ op: "addAnnot", args: cloud },
{ op: "addAnnot", args: arrow },
{ op: "addAnnot", args: underline },
]);
return doc.save({ mode: "incremental" });
}
Page 1 of draw_on_page.pdf
Open draw_on_page.pdf (2 pages, 29 KB)

The result is the original bytes, unchanged, followed by one revision. The Q2 row sits in a red cloud, a red arrow points at the chart from the space beside it, and a hand-drawn wave runs under “Total sales”.

  • Each method gives an edit with a 1-point red outline and nothing filled. Change its spec before you apply it: the border’s width and style (solid, dashed with a pattern, or cloudy with an intensity), the interior colour that fills a shape or a closed arrowhead, and a line’s ends.
  • inkAt takes one list of points per stroke and draws a smooth curve through them, as a pen does. Lamina PDF drops each point less than 0.25 pt from the last one it kept, so a pen that reports every pixel doesn’t bloat the file.
  • Lamina PDF draws every mark itself and stores the drawing in the file, so every reader that draws stored appearances, as pdf.js, PDFium and Acrobat do, shows the same mark. The cloud’s bumps and the arrowheads are drawn at sizes taken from the border’s width and intensity.
  • The report is a tagged PDF, the kind screen readers follow. A drawing marks no text, so give each one a description (contents) that says what it means. The mark joins the document’s structure, and a screen reader reads the description.
  • The author and dates come from your code, never from a clock inside Lamina PDF, so the same edit gives the same file wherever it runs.
  • A circle: pass "circle" to shapeAt. It draws the ellipse inside the box.
  • Another line ending: ends takes two of none, square, circle, diamond, openArrow, closedArrow, butt, rOpenArrow, rClosedArrow and slash, for the start and the end.
  • A measured line: set the line’s leader to draw it a set distance from its two points, with a leader line back to each, like a dimension on a technical drawing.
  • A polygon or polyline: polyAt with "polygon" closes the shape through at least three points, and "polyLine" leaves it open, with endings like a line’s.
  • A pressure-sensitive pen: give each stroke of the ink spec its widths, one per point. Lamina PDF fills the stroke as an outline that swells and thins with them. Lamina PDF stores the widths under /LMNA_Widths, a key of its own. Other readers show the stored drawing. A tool that draws the mark again from its keys uses the single width.
  • Erase a stroke: updateAnnot with an ink patch removes strokes by their place in the list (remove) and adds new ones (add). Lamina PDF draws the mark again.
  • A PDF/A or PDF/UA file: the marks keep the file’s claims, and doc.plan() warns before you save when an edit breaks one. A mark with no description breaks PDF/UA (annot-without-contents).

Next: answer a review, which reads these marks back as comments.

Add a text box

You’ll type on a report’s first page: a callout pointing at the chart, and a yellow note beside the total with one word in bold. You need this for a text tool in an editor, or a script that adds a review note to every file it checks.

Viewers report where a pointer went in page space: points from the page’s top-left corner. textBoxAt and calloutAt turn a box and points there into the edit that adds a text box, in the page’s user space:

packages/sdk/examples/add-text-box.ts
// Type on a page: a callout pointing at the chart, and a filled note beside the total with one
// word in bold.
// The boxes and points are in page space (points from the page's top-left), as a viewer reports
// where a pointer went. The boxes are in Helvetica, which every reader has, so the WebAssembly
// extract module can draw them too.
import { type AnnotColor, type AnnotCommon, Document, type RichText } from "@laminapdf/sdk";
// Where the boxes go on the example's input, the quarterly report, in points from the page's
// top-left: for your own file, take them from your viewer's pointer.
/** The callout's box, in the space right of the chart: `[x0, y0, x1, y1]`. */
const CALLOUT = [330, 168, 500, 190] as const;
/** The callout's line: from the chart's right edge, through a knee, to the box. */
const LEADER = [
[257, 200],
[300, 179],
[330, 179],
] as const;
/** The note beside the total. */
const NOTE = [300, 452, 520, 486] as const;
/** A pale yellow, like a sticky note. */
const YELLOW: AnnotColor = [1, 0.96, 0.7];
/**
* The document with a callout and a note typed on its first page, saved incrementally. `at` is
* when the boxes were typed, as a PDF date.
*/
export function addTextBox(bytes: Uint8Array, at: string): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const byMe = (): AnnotCommon => ({ author: "Ada Lovelace", created: at, modified: at });
const callout = doc.calloutAt(0, CALLOUT, LEADER, "Label the chart's axes");
callout.common = byMe();
const text: RichText = [
[{ text: "Check: " }, { text: "€ 4,300", bold: true }, { text: " should match the table's total." }],
];
const note = doc.textBoxAt(0, NOTE, text);
if (note.spec.type === "freeText") note.spec.fill = YELLOW;
note.common = byMe();
doc.apply([
{ op: "addAnnot", args: callout },
{ op: "addAnnot", args: note },
]);
return doc.save({ mode: "incremental" });
}
Page 1 of add_text_box.pdf
Open add_text_box.pdf (2 pages, 27 KB)

The result is the original bytes, unchanged, followed by one revision. A callout reading “Label the chart’s axes” points at the chart’s right edge, and a yellow note beside the total puts “€ 4,300” in bold.

  • Each method gives an edit for a box in 12-point Helvetica, left-aligned, with a 1-point border. Change its spec before you apply it: the font, size, align, the fill behind the text and the border.
  • The text is a string, a paragraph per line, or rich text: an array of paragraphs, each an array of spans that can be bold or italic. Lamina PDF breaks lines at the box’s width.
  • Lamina PDF draws every box itself and stores the drawing in the file, so every reader that draws stored appearances, as pdf.js, PDFium and Acrobat do, shows the same box. The text is upright as the page is shown, even on a turned page.
  • A box keeps its text in the keys other apps read too: the plain text as its description, its font, size and colour, and the bold and italic words as rich text. An app that draws boxes itself from those keys shows plain text where it ignores rich text.
  • The author and dates come from your code, never from a clock inside Lamina PDF, so the same edit gives the same file wherever it runs.
  • Another font: set spec.font to "times" or "courier", which every reader has. For any other font, add its bytes with addBlob and set spec.font to the ID it returns. Lamina PDF embeds the characters the box uses.
  • Characters the font lacks: set spec.fallbacks to the IDs of fonts that have them, for example a Noto font for Chinese or Arabic. A character no font has fails the edit with annotation-glyph-missing.
  • Typewriter text: set spec.intent to { type: "typewriter" } for text with no border or fill, as when filling in a form that has no fields. Its lines end only where yours do, never at the box’s edge, as in Acrobat’s typewriter tool.
  • Change a box later: updateAnnot with a freeText patch replaces its text, font, size or any other field, and Lamina PDF draws it again. A box’s contents are its text, so change them with the patch’s text. A box another app made keeps its look until you change it. Then Lamina PDF keeps its paragraphs, bold and italic, and warns with rich-text-simplified when the box held more.
  • In the browser: boxes in Helvetica, Times and Courier work in the extract and text modules. A font given by its bytes, and fallback fonts, need the text module: open the document after init({ text: true }). Elsewhere the edit fails with appearance-needs-text.
  • A PDF/A file: Helvetica, Times and Courier aren’t embedded, which PDF/A forbids, so doc.plan() warns with pdfa-font-not-embedded. Give the box a font by its bytes instead.

Next: draw on a page, with ink, shapes and arrows made the same way.

Stamp a page and attach a file

You’ll approve a report: a green stamp reading “APPROVED by Ada Lovelace” beside its title, and the table’s figures attached as a CSV file next to the table. You need this for a review tool that signs off on documents, or a script that files a report’s data inside it.

stampAt takes a box in page space and attachFileAt takes a point there, the way a viewer reports where a pointer went. Each gives the edit that adds the annotation:

packages/sdk/examples/stamp-and-attach.ts
// Approve a report: a stamp with the approver's name at the top of its first page, and the
// table's figures attached as a CSV file beside the table.
// The box and the point are in page space (points from the page's top-left), as a viewer
// reports where a pointer went. The stamp's lines are set in Helvetica, which every reader has,
// so the WebAssembly extract module can draw it too.
import { type AnnotCommon, Document } from "@laminapdf/sdk";
// Where the marks go on the example's input, the quarterly report, in points from the page's
// top-left: for your own file, take them from your viewer's pointer.
/** The stamp, right of the title: `[x0, y0, x1, y1]`. */
const STAMP = [370, 56, 540, 106] as const;
/** The attachment's icon, right of the table's last column. */
const ICON = [370, 282] as const;
/** The table's figures. */
const FIGURES = "Quarter,Units,Sales\nQ1,120,1200\nQ2,310,3100\n";
/**
* The document approved: a stamp and an attached file on its first page, saved incrementally.
* `at` is when it was approved, as a PDF date.
*/
export function stampAndAttach(bytes: Uint8Array, at: string): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const byMe = (): AnnotCommon => ({ author: "Ada Lovelace", created: at, modified: at });
// The stamp's lines are written into it now and never change, as on a rubber stamp.
const stamp = doc.stampAt(0, STAMP, { dynamic: { lines: ["APPROVED", "by Ada Lovelace"], style: "green" } });
stamp.common = byMe();
const attach = doc.attachFileAt(0, ICON, "figures.csv", new TextEncoder().encode(FIGURES), "text/csv");
if (attach.spec.type === "fileAttachment") {
attach.spec.icon = "graph";
attach.spec.file.description = "The table's figures";
attach.spec.file.modified = at;
}
attach.common = byMe();
doc.apply([
{ op: "addAnnot", args: stamp },
{ op: "addAnnot", args: attach },
]);
return doc.save({ mode: "incremental" });
}
Page 1 of stamp_and_attach.pdf
Open stamp_and_attach.pdf (2 pages, 26 KB)

The result is the original bytes, unchanged, followed by one revision. The stamp sits right of the title, and a small bar-chart icon beside the table holds figures.csv.

  • A stamp shows one of three things. A standard stamp shows a name such as approved, draft or confidential in capitals inside a frame of its colour. An image stamp shows a JPEG or PNG fitted to its box. A dynamic stamp shows your own lines, the first in bold.
  • Lamina PDF draws every stamp and icon itself and stores the drawing in the file, so every reader that draws stored appearances, as pdf.js and PDFium do, shows the same picture. A standard stamp’s letters are drawn as shapes, so the stamp needs no font.
  • A dynamic stamp’s lines are fixed when you make the edit, as on a rubber stamp. Lamina PDF never runs a script to fill in a name or a time, so build the lines from your user’s name and your clock.
  • Lamina PDF stores the attached file’s bytes exactly as given, with their size and a checksum. The document’s attachments list it, held by the icon, and attachmentBytes gives the bytes back. Lamina PDF never opens an attached file.
  • A screen reader reads each annotation’s contents. Unless you give them, a stamp’s contents are its name or its lines, and an attachment’s are the file’s name.
  • A standard stamp: pass { standard: "approved" }, or another of the sixteen names, such as notApproved, confidential or forComment; the StampName type lists them all. Set the edit’s common.color to draw it in another colour.
  • Your own image: add a PNG or JPEG with addBlob, then pass { image: id }. A PNG keeps its transparency. Other image formats fail the edit with stamp-image-invalid.
  • The icon: set spec.icon to "paperclip", "pushPin", "graph" or "tag". Change it later with updateAnnot and a fileAttachment patch.
  • In the browser: standard and image stamps and attachments work in every module. A dynamic stamp needs the extract or text module; in the base module the edit fails with appearance-needs-text.
  • A PDF/A file: PDF/A-1 and PDF/A-2 forbid attached files, so doc.plan() warns with pdfa-attachment-forbidden. PDF/A-3 allows them with a modified date and a MIME type. A dynamic stamp’s Helvetica isn’t embedded, which PDF/A forbids, so doc.plan() warns with pdfa-font-not-embedded; use a standard stamp there.
  • Sound comments: older PDFs can hold recorded comments. pageAnnotations lists them with their format and length, and soundAsWav(id) returns the recording as a WAV file, which every browser’s <audio> element plays.

Next: review comments, to answer and resolve the comments on a page.

Place images and shapes on a page

You’ll brand a report: a pale band behind its title, the company’s logo over the band’s right end, and its wordmark at the foot of the page. You need this to letterhead documents, put a logo on generated reports, or let people place pictures and shapes on pages.

Each object becomes part of the page, as if the page had been made with it. Unlike a stamp or a comment, it prints, every reader draws it, and no one can hide it. The code adds a band, a logo and a wordmark to the report’s first page:

packages/sdk/examples/place-content.ts
// Brand a report: a pale band behind its title, the company's logo over the band's right end,
// and its wordmark, a page of another PDF kept as vectors and text, at the foot of the page.
// Each is placed as page content, not as a comment: it prints and every reader draws it. The
// boxes are in page space (points from the page's top-left), as a viewer reports where a
// pointer went. In this tagged report the logo and the wordmark are figures with alternate
// text, and the band is decoration, which screen readers skip.
import { Document } from "@laminapdf/sdk";
// Where each goes on the example's input, the quarterly report, in points from the page's
// top-left: for your own file, take them from your viewer's pointer.
/** The band behind the title: `[x0, y0, x1, y1]`. */
const BAND = [44, 68, 551, 110] as const;
/** The logo, over the band's right end, as wide again as it is tall, as the image is. */
const LOGO = [455, 65, 551, 113] as const;
/** The wordmark, at the foot of the page, the size of its page. */
const WORDMARK = [56, 740, 176, 800] as const;
/** The matrix that stretches an image's or a page's unit square to the box `[x0, y0, x1, y1]`. */
function to([x0, y0, x1, y1]: readonly [number, number, number, number]) {
return [x1 - x0, 0, 0, y1 - y0, x0, y0] as const;
}
/**
* The document branded: a band, a logo and a wordmark on its first page, saved incrementally.
* `at` is when it was branded, as a PDF date.
*/
export function placeContent(
bytes: Uint8Array,
logo: Uint8Array,
wordmark: Uint8Array,
at: string,
): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
// Behind the page's own content, so the title stays on top of it.
doc.content.add(0, {
id: "title-band",
object: {
shape: { path: { rect: { rect: [...BAND], radius: 6 } }, fill: [0.89, 0.93, 0.98] },
},
matrix: [1, 0, 0, 1, 0, 0],
layer: "behind",
alt: "decorative",
modified: at,
});
doc.content.add(0, {
id: "logo",
object: { image: { blob: doc.addBlob(logo) } },
matrix: to(LOGO),
alt: { text: "Northwind Traders" },
modified: at,
});
doc.content.add(0, {
id: "wordmark",
object: { form: { blob: doc.addBlob(wordmark), page: 0 } },
matrix: to(WORDMARK),
alt: { text: "Northwind, the company's wordmark" },
modified: at,
});
return doc.save({ mode: "incremental" });
}
Page 1 of place_content.pdf
Open place_content.pdf (2 pages, 28 KB)

The result is the original bytes, unchanged, followed by one revision. The band sits behind the title, the logo’s transparent PNG edges let the band show through at its right end, and the wordmark stays sharp at any zoom because it is still vectors and text.

  • You name each object with an ID of your own, unique on its page. Lamina PDF stores the ID with the object, so content.update and content.remove find it again after the file is saved and reopened, and content.added lists what a page holds.
  • An object’s matrix places it on the page, in page space: points from the page’s top-left corner as shown, with y going down. A picture or a page of another PDF fills a square one point wide, so the matrix [w, 0, 0, h, x, y] draws it w by h points with its top-left corner at (x, y). A shape’s points are already in page space, so the identity matrix [1, 0, 0, 1, 0, 0] draws it where they are. Turn or mirror an object by changing the matrix.
  • Lamina PDF never rewrites the page’s own content. It draws each object with a few drawing instructions of its own, added after the page’s content, or before it for the behind layer. The page’s text and pictures keep their bytes, and an object moves without touching anything else.
  • In a tagged file, an object with alternate text becomes a figure that screen readers announce, and one marked "decorative" is skipped. A file that claims PDF/UA-1 requires one or the other for a picture, and refuses it otherwise with content-needs-alt-text.
  • A shape: give its path as { line }, { rect } (with an optional corner radius), { ellipse } or { polygon }, filled with fill, outlined with stroke, or both. A stroke’s dash is "solid", "dashed" or "dotted".
  • Move, resize or turn an object later: content.update(index, id, { matrix, modified }). The same call takes opacity, an image’s crop (the part of its square that shows), a shape’s fill and stroke, and new bytes in blob. Its order is the object’s place among those on its layer: 0 sends it to the back and -1 brings it to the front.
  • Fade it: give opacity from 0 to 1. A file that claims PDF/A-1 forbids see-through objects, so doc.plan() warns with pdfa-transparency; later PDF/A parts allow them.
  • Remove it: content.remove(index, id). An incremental save keeps the file’s earlier revisions, and the object stays in them; save with mode: "fullRewrite" to write the file without it.
  • Image formats: JPEG and PNG work, and a PNG keeps its transparency. Convert other formats first; anything else fails with content-object-invalid.
  • Protected PDFs: some PDFs need a password or forbid copying. To place a page of one, call addSource with its bytes and the password; only the permissions password lifts a limit. Then use the ID it returns as the object’s blob. The password stays out of the edit and out of the saved file. See owner-password-required.
  • In the browser: placing objects works in every module, the base module included.

Next: edit what a page draws, to move and change the objects a page already had.

Add text to a page

You’ll type two lines on a report’s first page: a note in Helvetica with one bold word, and a greeting in two scripts. You need this for an editor’s text tool, a script that stamps a line on every page, or a document that has no form fields.

Unlike a text box, which is a comment, this text becomes part of the page: it prints, every reader draws it, and no one can hide it. A box in page space, points from the page’s top-left corner as a viewer reports where a pointer went, says where it goes:

packages/sdk/examples/add-text.ts
// Type on a page as page content: a note in Helvetica with one bold word, and a greeting in two
// scripts set in fonts given by their bytes, the second font drawing the Arabic the first lacks.
// The text becomes part of the page: it prints, every reader draws it, and it copies and searches
// as typed. The boxes are in page space (points from the page's top-left), as a viewer reports
// where a pointer went. In this tagged report each text is a paragraph that screen readers read.
// Fonts given by their bytes need the WebAssembly text module; Helvetica, Times and Courier need
// no bytes.
import { Document } from "@laminapdf/sdk";
// Where the texts go on the example's input, the quarterly report, in points from the page's
// top-left: for your own file, take them from your viewer's pointer.
/** The note: `[x0, y0, x1, y1]`. */
const NOTE = [56, 690, 300, 712] as const;
/** The greeting, under the note. */
const GREETING = [56, 718, 300, 746] as const;
/** The size of the greeting, in points. */
const GREETING_SIZE = 16;
/**
* The document with a note and a greeting typed on its first page, saved incrementally. `at` is
* when they were typed, as a PDF date.
*/
export function addText(bytes: Uint8Array, latin: Uint8Array, arabic: Uint8Array, at: string): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
doc.content.addText(0, {
id: "note",
rect: NOTE,
runs: [{ text: "Reviewed " }, { text: "twice", bold: true }],
fonts: ["helvetica"],
modified: at,
});
// The first font draws the Latin, the second what the first lacks.
doc.content.addText(0, {
id: "greeting",
rect: GREETING,
runs: [{ text: "Hello مرحبا" }],
fonts: [doc.addBlob(latin), doc.addBlob(arabic)],
size: GREETING_SIZE,
modified: at,
});
return doc.save({ mode: "incremental" });
}
Page 1 of add_text.pdf
Open add_text.pdf (2 pages, 35 KB)

The result is the original bytes, unchanged, followed by one revision. The greeting’s Latin letters come from the first font and the Arabic from the second, so a font you pass never has to cover every script.

  • Fonts: fonts is the font, then the fallbacks. "helvetica", "times" and "courier" need no bytes and work in the extract and text modules. For any other font, add its bytes with addBlob and name the ID it returns. Lamina PDF embeds the part of the font the text uses, with a map that makes the text copy and search as typed.
  • Fallbacks: each character is drawn in the first font of the chain that has it, so one list can hold a Latin font, a symbol font and the font of another script. A character no font has fails the edit with content-glyph-missing, never a blank.
  • Layout: the text is shaped and wrapped at the box’s width, right to left where the script runs that way. It starts at the top of the box and is clipped to it, so make the box tall enough.
  • Tagging: in a tagged file the text is a paragraph that screen readers read, or decoration they skip for tag: "artifact". A file that claims PDF/UA-1 also needs every font embedded (ISO 14289-1 §7.21.4.1): text in Helvetica, Times or Courier is not, so add the font’s bytes for such a file. Lamina PDF does not check this when it adds the text.
  • Finding it again: Lamina PDF stores each text’s ID and what it says with the text. After a save and a reopen, content.added lists it and content.update and content.remove change it.
  • A font that forbids embedding: a font file declares in its OS/2 table whether it may be embedded. One that forbids it fails the edit with content-font-not-embeddable; choose another font. Bytes that aren’t a TrueType or OpenType font, such as a WOFF2 file, fail with content-font-invalid.
  • Size, colour and alignment: size is in points, color a gray, RGB or CMYK array, and align is "left", "center" or "right".
  • Change the text later: content.update(index, id, { text, modified }) replaces the box, runs, fonts, size and colour, and matrix moves or turns it. content.remove(index, id) takes it off; an incremental save keeps the earlier revisions, and the text stays in them.
  • In the browser: Helvetica, Times and Courier work in the extract and text modules. A font given by its bytes needs the text module: open the document after init({ text: true }). Elsewhere the edit fails with appearance-needs-text.
  • A PDF/A file: Helvetica, Times and Courier aren’t embedded, which PDF/A forbids, so doc.plan() warns with pdfa-font-not-embedded. Give the text a font by its bytes instead.

Next: place images and shapes in the same way.

Add watermarks, headers, footers and Bates numbers

You’ll mark every page of a report with a faint CONFIDENTIAL, the file’s name and date, “Page 1 of 2” and a Bates number. You need this for a legal production, a review copy, or a menu item that stamps a whole document.

Like added text, a mark becomes part of the page: it prints and every reader draws it. One edit marks many pages, so you name the pages, counted from 0:

packages/sdk/examples/add-page-marks.ts
// Put the same marks on every page of a document: a hideable CONFIDENTIAL watermark, a header with
// the file's name and the date, a footer that numbers the pages, and a Bates number in the corner
// of each page.
//
// The marks become part of each page: they print and every reader draws them. The watermark sits
// in an optional content group, so a reader's layers panel can switch it off, and in a tagged file
// like this PDF/A-2 and PDF/UA-1 archive every mark is an artifact that screen readers skip. A header's `{page}` and
// `{pages}` are filled when the edit is applied; the Bates numbers count from where you say
// (number a second file from where the first ended). The marks stay changeable after a save:
// `doc.content.pageMarks(index)` lists them by the IDs below.
import { Document } from "@laminapdf/sdk";
/**
* The document with its pages marked, saved incrementally, all in the font `font` (a TrueType or
* OpenType file), which PDF/A and PDF/UA files need embedded. `at` is when the marks were made, as a
* PDF date; `file` and `date` are what the header's `{file}` and `{date}` stand for, as you want
* them written.
*/
export function addPageMarks(
bytes: Uint8Array,
font: Uint8Array,
file: string,
date: string,
at: string,
): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const fonts = [doc.addBlob(font)];
// Every page, counted from 0.
const pages = Array.from({ length: doc.pageCount }, (_, i) => i);
// A red CONFIDENTIAL across each page, turned 45 degrees and faint, which a reader can hide.
doc.content.addWatermark(pages, {
id: "confidential",
mark: { text: { text: "CONFIDENTIAL", fonts, size: 90, color: [0.8, 0.1, 0.1] } },
opacity: 0.2,
angle: 45,
hideable: true,
modified: at,
});
// The file's name and the date at the top right, and the page's number at the bottom centre,
// clear of this report's own header at the top left and page number at the bottom right: slots in
// the order top left, centre, right, then bottom left, centre, right.
doc.content.setHeaderFooter(pages, {
id: "folio",
slots: [null, null, "{file} · {date}", null, "Page {page} of {pages}", null],
fonts,
size: 9,
color: [0.35],
date,
file,
modified: at,
});
// ACME-000101, ACME-000102 and on, at the bottom left.
doc.content.applyBates(pages, {
id: "bates",
prefix: "ACME-",
start: 101,
digits: 6,
slot: "bottomLeft",
fonts,
size: 9,
modified: at,
});
return doc.save({ mode: "incremental" });
}
Page 1 of add_page_marks.pdf
Open add_page_marks.pdf (1 page, 35 KB)

The result is the original bytes, unchanged, followed by one revision. The watermark sits in a layer, so a reader’s layers panel can switch it off.

  • Watermarks and backgrounds: a watermark is drawn in front of each page’s content and a background behind it. Each shows text, centred on the page and turned by angle degrees counterclockwise, or an image: a watermark shows it whole inside most of the page, a background covers the page with it. Add an image’s bytes with addBlob first.
  • Fields: a header or footer slot’s text may hold {page}, {pages}, {label} (the page’s label, else its number), {date} and {file}. You give {date} and {file} as text, so the same call writes the same bytes everywhere. {{ and }} are braces. The fields are filled when you apply the edit, so a page you move later keeps its number: apply the mark again with updatePageMark to number it afresh.
  • Slots: a header and footer has six slots in the order top left, centre, right, then bottom left, centre, right. Each is one line, left, centred or right aligned, between the margins (36 points unless you say otherwise). The three slots on an edge overlap, so a long text runs past its third of the page.
  • Bates numbers: start is the first page’s number, and each page after it counts one more, in the order you name the pages. To number a second file where the first ended, apply the edit to it with the next start. The number is padded with zeros to digits, 6 unless you say otherwise (0 for none); a wider number is not cut.
  • Fonts: as for added text, fonts is the font, then its fallbacks, in Helvetica when absent. A font you give by its bytes is embedded once for the whole mark, as one subset of the glyphs every page uses, however many pages differ in their text (page numbers, Bates numbers). Helvetica, Times and Courier need no bytes.
  • Tagging: in a tagged file every mark is an artifact: a watermark, a background, a header, a footer or a Bates number. Screen readers skip it, and it joins no structure. A mark with text in both bands is pagination on the page, with its header part and its footer part each an artifact of its own.
  • Finding them again: Lamina PDF stores each mark’s ID and what it says with the mark. After a save and a reopen, content.pageMarks(index) lists a page’s marks, content.updatePageMark(pages, id, mark, modified) replaces one on the pages you name, and content.deletePageMark(pages, id) takes it off. An incremental save keeps the earlier revisions, and the mark stays in them.
  • Opacity and angle: opacity is from 0 to 1 and angle from -360 to 360 degrees.
  • A layer a reader can hide: hideable: true puts the mark in an optional content group, so a reader’s layers panel can switch it off. Deleting the mark from the last page that has it takes the layer out of the file. A PDF/A-1 file can’t hold layers: doc.plan() warns with pdfa-optional-content.
  • A different mark of the same kind: updatePageMark takes the new mark as { watermark }, { background }, { headerFooter } or { bates }; a mark of another kind fails with invalid-op, and a page without the mark with unknown-page-mark.
  • Colour and margins: color is a gray, RGB or CMYK array, and margins is { top, right, bottom, left } in points.
  • A signed file: like every change to a page, a mark breaks a certified file’s signature, and an approval-signed file takes it in a revision after the signature.
  • A PDF/A file: Helvetica, Times and Courier aren’t embedded, which PDF/A forbids, so doc.plan() warns with pdfa-font-not-embedded. Give the mark a font by its bytes instead.

Next: add text to a page in the same way.

Record your own metadata

You’ll record a review in a PDF’s XMP metadata: its status, its reviewers and the review round, as properties of your own. You need this when a workflow tracks facts a PDF has no field for, such as an approval, a case number or a retention date.

XMP metadata is the XML copy of a PDF’s metadata. Besides the title and authors, it holds any property a namespace defines, and a namespace is a URI you own, so your names can’t clash with anyone else’s. This example edits an archive-ready PDF/A file:

packages/sdk/examples/edit-xmp.ts
// Record a review in a document's XMP metadata: properties of your own, beyond the title and
// authors, which a PDF/A file keeps without losing its claim.
// Each property is named by a namespace you own and a local name. In a PDF/A file, Lamina PDF also
// declares each new property in the metadata's extension schemas, as PDF/A requires, and the edit
// lists what it declared.
import { Document } from "@laminapdf/sdk";
/** The namespace of the review properties: a URI you own, so they can't clash with anyone else's. */
const REVIEW = "https://example.com/ns/review/1.0/";
/**
* The document with the review recorded in its XMP metadata, saved incrementally.
*
* @param savedAt - the time of the save, as a PDF date (`D:20261110093000Z`) your app takes
* from its clock.
*/
export function editXmp(bytes: Uint8Array, savedAt: string): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const reviewers = [
{ type: "text", value: "Ada Lovelace" },
{ type: "text", value: "Charles Babbage" },
] as const;
const edits = [
doc.setXmpProperty(REVIEW, "review", "status", { type: "text", value: "Approved" }),
doc.setXmpProperty(REVIEW, "review", "reviewers", { type: "seq", value: [...reviewers] }),
doc.setXmpProperty(REVIEW, "review", "round", { type: "integer", value: 2 }),
];
for (const property of edits.flatMap((edited) => edited.declared)) {
console.warn(`declared ${property.prefix}:${property.name} as ${property.valueType}`);
}
return doc.save({ mode: "incremental", metadataDate: savedAt });
}
Page 1 of edit_xmp.pdf
Open edit_xmp.pdf (1 page, 18 KB)

The result is the original bytes followed by one revision. Its XMP metadata holds review:status, review:reviewers and review:round, and still meets PDF/A-2b.

  • setXmpProperty(namespace, prefix, name, value) (SetXmpProperty in Rust) sets one property. prefix is the short name the XML writes for the namespace, used when the metadata has none for it yet.
  • A value carries its type: { type: "text", value: "Approved" }. The types are text, uri, integer, real, boolean, date (a PDF date), langAlt (the same text in several languages), and seq and bag, ordered and unordered lists of one type.
  • PDF/A allows only the properties its standard names, unless the metadata declares the others in an extension schema. Lamina PDF writes that declaration for each new property, and the edit’s declared lists them.
  • A file without XMP metadata gets it with the first property you set.
  • Remove a property: removeXmpProperty(namespace, name). As with any removal, an incremental save keeps the old value in the file’s earlier revisions; save with mode: "fullRewrite" to drop it.
  • Title, authors and dates: use setMetadata. setXmpProperty on dc:title works too and keeps the Info dictionary in step, but only with the value type the field needs: text for the title, a seq of text for the authors.
  • Structures and comments: read the metadata with xmpPacket(), change its XML, and write it back with replaceXmpPacket(xml). XML that doesn’t parse is refused with invalid-xmp-packet, and nothing changes.
  • The PDF/A or PDF/UA claim itself: an edit can’t change it (xmp-claim-read-only). Only converting or checking the file makes that claim.

Next: save a PDF, for what a signed or repaired file allows.

Organise pages

You’ll delete a PDF’s third page, move its last page to the front, add a blank page at the end and turn two pages a quarter clockwise, in one edit. Use it for a page organiser, a scan out of order, or a pipeline that drops cover pages.

Each page has an ID, such as p12.0, that stays the same while other pages move, so each step names its pages by the IDs read before the edit:

packages/sdk/examples/organise-pages.ts
// Organise a document's pages: delete one, move one to the front, add a blank page at the end
// and turn two pages a quarter clockwise, in one edit that one undo reverts.
//
// Pages are named by their IDs, which stay the same while other pages move. Deleting a page
// points the bookmarks, links and named destinations that went to it at the nearest page left,
// and the edit lists each one, so an app can say what moved.
import { Document } from "@laminapdf/sdk";
/** US Letter, in points. */
const LETTER = { width: 612, height: 792 };
/**
* The document with its third page deleted, its last page moved to the front, a blank Letter
* page added at the end and its first two pages turned a quarter clockwise. Needs `init()`.
*/
export function organisePages(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const ids = doc.pages.map((page) => page.id);
const [first, second, third] = ids;
const last = ids.at(-1);
if (first === undefined || second === undefined || third === undefined || last === undefined) {
throw new Error("the document needs at least three pages");
}
// One transaction: every op applies, in order, or none does. Each op names its pages by the
// IDs read before the edit, which the moves and the deletion leave as they are.
const edited = doc.apply([
{ op: "deletePages", args: { pages: [third] } },
{ op: "movePages", args: { pages: [last], to: "start" } },
{ op: "insertBlankPages", args: { at: "end", count: 1, size: LETTER, rotate: 0 } },
{ op: "rotatePages", args: { pages: [first, second], angle: 90, mode: "turn" } },
]);
for (const reference of edited.references) {
if (reference.outcome === "retargeted") {
console.warn(`${reference.kind} now points to page ${reference.to}`);
}
}
return doc.save();
}
Page 1 of organise_pages.pdf
Open organise_pages.pdf (5 pages, 6 KB)

The result has five pages: the old last page, then the old first and second pages turned on their side, then the old fourth page, then a blank Letter page. The bookmarks, links and named destinations that went to the deleted page now go to the old fourth page, and the program prints each one.

  • doc.pages lists the pages in order, each with its id. A page keeps its ID when it moves, and a new blank page gets a new one.
  • deletePages (DeletePages in Rust) deletes pages by ID. The bookmarks, links, named destinations and opening view that pointed at a deleted page now point at the nearest page left (the next one, or the one before if none follows), shown whole. The edit’s references lists each of them with where it now goes.
  • movePages (MovePages) moves pages to "start", "end", or before or after another page, in the order you list them.
  • insertBlankPages (InsertBlankPages) adds pages of a size in points: 612 × 792 is US Letter. In a document with page labels, such as roman numerals for the front matter, the new pages continue the numbering where they land, and every other page keeps its label.
  • rotatePages (RotatePages) with mode: "turn" adds the angle to each page’s own rotation, as rotate left and rotate right do. Without it, each page shows at the angle you give.
  • apply runs the steps in order as one edit: if one fails, none of them apply, and one undo() reverts them all. The edit’s pageOrder lists the page IDs in their new order.
  • Remove what pointed at a deleted page: pass references: "remove" to deletePages. A bookmark keeps its title but goes nowhere, and a link to the page stays on its own page but goes nowhere.
  • Reverse the order: reversePages with every page’s ID reverses the document. With some of them, those pages reverse among the places they hold, and the others stay put.
  • One step at a time: doc.deletePages(ids), doc.movePages(ids, "start") and the others each apply one step as its own edit, and doc.transact(tx => …) collects several of them into one.
  • Delete every page: you can’t. A PDF needs at least one page, so the edit refuses with no-pages-left and changes nothing.
  • Delete pages for good: an incremental save keeps the deleted pages in the file’s earlier revisions. Save with mode: "fullRewrite" to drop them.

Next: save a PDF, for what a signed file allows.

Duplicate pages

You’ll add a copy of a form’s first page at the end, so a second person can fill in the copy without changing the original. Use it for a sign-up sheet that needs another page, a template page repeated in a report, or a form filled in twice.

A copy shows the same content as its page, but its form fields are new: each gets the original’s name with #2 added, or the next free number. A copy of a copy continues the series: name#3. The program prints the name of each field the copy got:

packages/sdk/examples/duplicate-pages.ts
// Duplicate a form page, so a second copy can be filled in on its own.
//
// A copy shares its page's content but gets new annotations, so filling in a field on one page
// leaves the other alone: each copied field gets a name of its own, `<name>#2` (or the next free
// number). The edit lists each one, and each signature field it left out.
import { Document } from "@laminapdf/sdk";
/** The document with a copy of its first page added at the end. Needs `init()`. */
export function duplicatePages(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const first = doc.pages[0]?.id;
if (first === undefined) {
throw new Error("the document has no pages");
}
const edited = doc.duplicatePages([first], "end");
for (const field of edited.fields ?? []) {
if (field.outcome === "renamed") {
console.warn(`the copy's field is ${field.name}`);
} else {
console.warn(`field ${field.field} was not copied: it is a signature`);
}
}
return doc.save();
}
Page 1 of duplicate_pages.pdf
Open duplicate_pages.pdf (3 pages, 3 KB)

The result has three pages, and the third is a copy of the first. Its text field name#2 starts with the value the original had, Ada, and its checkbox agree#2 starts unticked. Typing into name#2 leaves name as it was.

  • duplicatePages (DuplicatePages in Rust) copies pages by ID to "start", "end", or before or after another page, in the order you list them. Each copy gets a new ID, listed in the edit’s pageOrder.
  • A copy shares its page’s content and resources, so the file grows by a few objects, not by the page’s images and fonts.
  • The copy’s links, notes and other annotations are new objects, so a viewer can select, edit or delete them on one page alone.
  • A form field shown on the copied page gets a new field with its own value. The edit’s fields lists each one with its new name.
  • In a document with page labels, a copy continues the numbering where it lands, and every other page keeps its label.
  • Copy several pages: list their IDs in the order you want the copies, and they land together at the place you give.
  • Signed forms: a signature’s field isn’t copied, since a signature signs one place in one file. The edit’s fields lists it as notCopied, and the copy shows no signature box.
  • Tagged documents: the copy gets tags of its own, so a screen reader reads it as it reads the original. Content of an element that runs on to another page, such as a paragraph that continues over the page break, stays untagged on the copy. The edit’s tagsIncomplete lists that copy. On a file that claims PDF/UA-1, saving then warns with duplicate-tags-incomplete.
  • Undo: one undo() removes every copy the edit made, with its fields.

Next: organise pages, to delete, move and rotate them too.

Edit what a page draws

You’ll change four things a page already draws: shrink a rectangle, delete a circle, move an image across the page and send a curve under everything else. Use it to tidy a generated page, move a logo, or remove a stray mark before you send a file on.

First, the program lists the page’s objects in painting order, each with its box and, when it can’t be moved, the reason. Each edit then names its object as the list gave it, and the four edits apply together:

packages/sdk/examples/edit-objects.ts
// Move, resize, delete and reorder what a page already draws.
//
// Lists the first page's objects, then changes four of them in one edit: shrinks the first
// shape about its centre, deletes the second, moves the last image across the page and sends
// the third shape, a line across the page, under everything else. Each edit names its object as
// the list does, and only the objects it names are written again: the rest of the page keeps its
// bytes. An object that would draw differently in its new place in the stacking order (another
// clip or transparency there) is refused with `content-not-editable`.
import { Document } from "@laminapdf/sdk";
/** The document with four objects of its first page changed. Needs `init({ extract: true })`. */
export function editObjects(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const objects = doc.content.objects(0);
for (const object of objects) {
console.log(object.kind, object.bounds, object.readOnly ? `(read-only: ${object.readOnly})` : "");
}
const [square, second, line] = objects.filter((o) => o.kind === "path");
const photo = objects.filter((o) => o.kind === "image").at(-1);
if (!square?.bounds || !second || !line || !photo) {
throw new Error("the page needs three shapes and an image");
}
// Page space: points from the top-left, y down. Half size, about the square's centre.
const [x0, y0, x1, y1] = square.bounds;
const [cx, cy] = [(x0 + x1) / 2, (y0 + y1) / 2];
doc.content.edit(0, [
{ transform: { object: square.object, matrix: [0.5, 0, 0, 0.5, cx - cx * 0.5, cy - cy * 0.5] } },
{ delete: { object: second.object } },
{ transform: { object: photo.object, matrix: [1, 0, 0, 1, 300, 0] } },
{ reorder: { object: line.object, to: "back" } },
]);
return doc.save();
}
Page 1 of edit_objects.pdf
Open edit_objects.pdf (1 page, 6 KB)

In the result, the red rectangle is half its size about the same centre, the blue circle is gone and the gradient image sits 300 points to the right. The dashed curve now paints first, under everything else; nothing overlaps it, so it looks the same.

  • content.objects(index) (content_objects in Rust) lists what the page draws: paths, text, images, forms and shadings. Boxes are in page space, points from the top-left of the page as shown, with y down. content.hitTest(index, [x, y]) gives the objects at a point, topmost first, and a rectangle [x0, y0, x1, y1] gives every object it meets.
  • An edit names an object by its place in the list and a hash of its bytes. So once an edit has changed an object, a name taken before that edit fails with content-object-stale, and an edit never lands on the wrong object.
  • A transform takes a matrix in page space: [1, 0, 0, 1, 300, 0] moves an object 300 points right, and [0.5, 0, 0, 0.5, e, f] halves it.
  • Only the objects you name are written again. The rest of the page keeps its bytes, and when another page draws the same content, that page stays as it was.
  • A resource nothing names any more, such as a deleted image’s stored picture, leaves the page’s resources.
  • Undo: one undo() reverts the whole edit.
  • Replace an image: add the new JPEG or PNG with addBlob(bytes) (add_blob), then edit { replaceImage: { object, blob } }. The new picture fills the same box.
  • Crop an image: { crop: { object, rect } } clips an image, a form or a shading to a rectangle in page space.
  • Stacking order: to takes "front", "back", { before: object } or { after: object }. A move that would put the object under another clip or other transparency, where it would draw differently, is refused with content-not-editable, and nothing changes.
  • Clipping objects: an object that clips what follows it can’t be moved or deleted; its readOnly says clipping-path.
  • Private content: a deleted object stays in the file’s earlier revisions until a full save. The edit’s stillInEarlierRevisions says so; save with mode: "fullRewrite" to drop it.

Next: crop pages, to hide part of every page instead.

Edit the text a page shows

You’ll change one word a page already shows: “world” becomes “Lamina PDF”. Use it to fix a typo, update a date or a price, or remove a line before you send a file on, without rebuilding the page.

First, the program lists the page’s runs of text, each with its line, font and, when it can’t be edited, the reason. It then picks the first run that says “world” and gives it new text:

packages/sdk/examples/edit-text.ts
// Change the text a page already shows, in the font it is set in.
//
// Lists the first page's runs of text, then rewrites the first one that says "world" to say
// "Lamina PDF" instead. The new text uses the font the run was set in, so every character must
// be one that font can draw; a character it can't is refused with `missing-glyph`, and a run
// that can't be edited at all (a Type 3 font, vertical text) says why. The text after the run
// moves by the difference in width; the lines below stay where they were.
import { Document } from "@laminapdf/sdk";
/** The document with "world" rewritten on its first page. Needs `init({ extract: true })`. */
export function editText(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const runs = doc.content.textRuns(0);
for (const run of runs) {
const readOnly = run.readOnly ? ` (read-only: ${run.readOnly})` : "";
console.log(`line ${run.line}: ${JSON.stringify(run.text)} in ${run.fontName} ${run.fontSize}${readOnly}`);
}
const run = runs.find((r) => !r.readOnly && r.text.includes("world"));
if (!run) {
throw new Error('no editable run says "world"');
}
doc.content.editText(0, run.run, run.text.replace("world", "Lamina PDF"));
return doc.save();
}
Page 1 of edit_text.pdf
Open edit_text.pdf (1 page, 2 KB)

In the result, the greeting reads “Hello, Lamina PDF!” in the same font and size. Text extraction, copy and search find the new words, since the page now shows them.

  • content.textRuns(index) (text_runs in Rust) lists the runs in the order the page draws them. A page draws its text in text objects, each a group of instructions that show glyphs. A run is the text one of those instructions shows in one font and size on one baseline; on a tagged page, a run also stays inside one tagged element. Its text has a space wherever the glyphs leave a word-sized gap.
  • An edit names a run by its text object and its glyphs within that object. Once an edit changes the object, a name taken before that edit fails with content-object-stale, so an edit never lands on the wrong text.
  • The new text uses the run’s own font. Every character must be one the font can draw: for an embedded subset, a character the document already shows in that font; for a font that isn’t embedded, any character of its encoding. Any other character fails with missing-glyph, and nothing changes, unless you name fonts that may draw it (change how text looks).
  • When the text grows or shrinks, the text after it in the same text object moves by the difference, and the lines below stay where they were. Another text object can place more text on the same line. That text stays put, so longer text can run into it: check the result.
  • A space the font has no glyph for becomes a word-sized gap, as typesetting programs write it.
  • Undo: one undo() reverts the edit.
  • Delete a run: give it empty text.
  • Change part of a run: name a smaller range of its glyphs, start to end. For most Western text, one character is one glyph.
  • Replace every match of a search: doc.content.replaceText(edits) changes many matches, on any pages, in one step and one undo. Each edit is a page, the glyphs the match covers (a run name with start and end set to the match) and its new text. It is all or nothing, so call doc.content.planReplaceText(edits) first: it lists each match’s report, or the error that makes it one to skip, and you send the others.
  • Read-only runs: a run can’t be edited when its font is a Type 3 font, writes vertically or has no map from its codes to text. Text that stands in for other text (ActualText), runs right to left, or has glyphs turned or written out of order can’t be edited either. Each such run’s readOnly says why, and editing it fails with content-not-editable.
  • Private content: the old text stays in the file’s earlier revisions until a full save. The edit’s stillInEarlierRevisions says so; save with mode: "fullRewrite" to drop it.

Next: change how the text looks, or edit what a page draws to move or delete whole objects.

Change how text a page shows looks

You’ll make one word on a page bold, red and underlined. Use it to flag a changed price, restyle a heading, or match a font before you send a file on, and the words stay as they were.

The program finds the first run that says “world”, names its five glyphs and gives them a style:

packages/sdk/examples/style-text.ts
// Change how text a page already shows looks: its weight, colour and underline.
//
// Finds the first run that says "world" and makes just that word bold, red and underlined,
// leaving the rest of the run as it was. A style names runs, or glyphs inside one, and changes
// only the fields it sets: a font family, a size, a colour, bold, italic, underline, raised or
// lowered text, and the alignment and spacing of the run's lines. The text itself doesn't change,
// so it still copies and searches as before. Bold and italic pick the face of a standard font
// such as Helvetica; for another font, name the bold face as the font.
import { Document } from "@laminapdf/sdk";
/** The document with "world" made bold, red and underlined on its first page. Needs `init({ extract: true })`. */
export function styleText(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const found = doc.content.textRuns(0).find((r) => !r.readOnly && r.text.includes("world"));
if (!found) {
throw new Error('no editable run says "world"');
}
// The run's glyphs are numbered from `run.start`; the word is five of them.
const at = found.text.indexOf("world");
const word = { ...found.run, start: found.run.start + at, end: found.run.start + at + 5 };
doc.content.setTextStyle(0, [word], { bold: true, color: [0.8, 0, 0], underline: true });
return doc.save();
}
Page 1 of style_text.pdf
Open style_text.pdf (1 page, 3 KB)

In the result, “Hello, world!” keeps its size and position; only “world” changes, and “!” follows it.

  • A style names runs, as editing text does, or glyphs inside a run. Each field is optional and changes only what it names.
  • font is "helvetica", "times", "courier" or the ID of a font’s bytes from addBlob. The run’s text is drawn again in that font as a new subset, so every character needs a glyph in it. The old font stays for the text that uses it.
  • bold and italic pick the face of a standard font. A font given by its bytes is one face: name the bold face as the font instead. A run whose own font has no faces to pick from (an embedded subset, a TrueType font) takes bold: true anyway. Its glyphs are drawn filled and stroked with a thin line, unless the font’s name already says bold.
  • On a font with no faces, italic: true shears the run by 12 degrees, unless the name already says italic or oblique. A run with a text rise can’t take it. bold: false and italic: false are refused on such a font, since neither can be taken off.
  • size is in points. baseline raises or lowers a run at 65 % of its size.
  • underline draws a line under the run as a path after the text. Lamina PDF can’t tell an underline from other lines, so it can’t take one off.
  • align and lineSpacing move the lines of the run’s text object. A line aligns to the widest extent of all the object’s lines; spacing is a multiple of the glyphs’ size.
  • Undo: one undo() reverts the style.

An edit that needs a character the run’s font lacks fails with missing-glyph, unless you name fonts that may draw it:

const plan = doc.content.planEditText(0, run, "naïve", ["helvetica"]);
// plan.substitutions: [{ text: "ï", font: "Helvetica", kind: "substitute" }]
doc.content.editText(0, run, "naïve", ["helvetica"]);
  • A full copy of the run’s own font (its bytes, from addBlob) adds a new subset of it. Any other font substitutes, and fidelity says "substituted".
  • planEditText says which characters and which font before you commit, so a font never changes silently. The edit’s textEdits report the same afterwards, with grewBy, the points the line grew by.
  • On a file that claims PDF/A, a font you add must be embedded: the standard 14 fonts aren’t, and the save warns with pdfa-font-not-embedded.

Next: add text to a page, to place new text instead.

Edit a tagged PDF

You’ll edit an accessible report that claims PDF/UA and save it with its claim still true. Lamina PDF keeps the file’s tags up to date as you edit, so screen readers still read the page in its order, and before you save it tells you which claims your edits broke.

The program deletes the report’s summary paragraph, renames its table’s heading and rewrites the alternative text of its chart. It then asks the save plan which claims no longer hold, and removes only those claims before saving:

packages/sdk/examples/edit-tagged-pdf.ts
// Edit an accessible (tagged, PDF/UA) document and keep its claim, or save without it.
//
// Deletes the summary paragraph of the report from `pdf-ua-report`, renames its table's heading
// and rewrites the alternative text of its chart. Lamina PDF keeps the tags in step: the deleted
// paragraph leaves the structure tree, and the heading's element still finds its text. Before
// saving, the plan lists the PDF/A and PDF/UA claims the edits broke; this example removes only
// those claims, so the file doesn't promise what it no longer meets.
import { Document } from "@laminapdf/sdk";
/** The report with its summary deleted, its table's heading renamed and its chart described anew. Needs `init({ extract: true })`. */
export function editTaggedPdf(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const runs = doc.content.textRuns(0);
const summary = runs.find((r) => r.text.startsWith("Sales grew"));
const heading = runs.find((r) => r.text === "Sales by quarter");
if (!summary || !heading) {
throw new Error("not the report from pdf-ua-report");
}
// Each edit names its run as the page is before it: the heading comes later on the page, so
// renaming it first leaves the summary's name as it was.
doc.content.editText(0, heading.run, "Quarterly sales");
// Empty text deletes the run, and the paragraph it was.
doc.content.editText(0, summary.run, "");
// The chart is the object that already has alternative text. Name it after the edits above,
// since deleting the summary renumbers the page's objects. Setting its text changes it for
// every object of the chart.
const chart = doc.content.objects(0).find((o) => o.alt !== undefined);
if (!chart) {
throw new Error("no chart");
}
doc.content.setAlt(0, chart.object, "Bar chart of quarterly sales: 120, 135, 160 and 150 thousand euros.");
// A `pdfa-…` code (and `imported-pdfa-unchecked`) breaks the PDF/A claim; the others, the
// PDF/UA claim.
const broken = doc.plan().conformanceWarnings.map((w) => w.code);
const pdfa = broken.some((code) => code.includes("pdfa"));
const pdfua = broken.some((code) => !code.includes("pdfa"));
if (pdfa || pdfua) {
console.warn(`the edits broke a claim: ${broken.join(", ")}`);
doc.removeConformanceClaims({ pdfa, pdfua });
}
return doc.save();
}
Page 1 of edit_tagged_pdf.pdf
Open edit_tagged_pdf.pdf (1 page, 13 KB)

In the result, the summary is gone, the heading reads “Quarterly sales” and a screen reader describes the chart with the new text. The file still meets PDF/UA-1, so it keeps its claim.

A tagged PDF marks each piece of a page’s content with a number, and its structure tree says which element (a heading, a paragraph, a figure) each number belongs to. Lamina PDF updates both as you edit:

  • Deleted content leaves the tree. Delete an object or a run of text, and its element no longer names it. An element left with no content leaves the tree too.
  • Moved and rewritten content keeps its place. An object you move, resize or reorder, and text you rewrite, stay in their elements.
  • Text alternatives follow the text. When you rewrite text whose element has a text alternative (ActualText or Alt) that holds the old words once, the new words replace them. An alternative that doesn’t hold them is removed, so a screen reader reads the new text itself.
  • You can describe a figure yourself. doc.content.setAlt() sets the alternative text of the figure that owns an object, and doc.content.objects() reports the text an object’s figure has now as alt. The text belongs to the figure, so every object of a chart drawn as many paths shares it.
  • A replaced figure needs new alternative text. The old text described the old image, so Lamina PDF removes it, and in a file that claims PDF/UA-1 the save plan warns with figure-without-alt until the figure has new text.

doc.plan().conformanceWarnings lists each PDF/A or PDF/UA claim the edits break. The warnings never block a save, so you choose what to do:

  • Fix it first: undo the edit that broke the claim. For a replaced figure, you can instead add alternative text with an accessibility tool and open the file again. The warning goes when the problem does.
  • Save without the claim: doc.removeConformanceClaims({ pdfua: true }) takes the claim out of the file’s XMP metadata, so the file no longer promises what it doesn’t meet. Set only the claims the warnings name, as the example does. This edit is the only one that may remove a claim; the other metadata edits refuse with xmp-claim-read-only. An incremental save keeps the old claim in the file’s earlier revisions; save with mode: "fullRewrite" to drop it.

Content edits can break a claim three ways: figure-without-alt for a replaced figure, content-tags-broken for content the page’s tags don’t cover, and pdfa-font-not-embedded for a font an edit added without embedding it (once edits can add fonts).

Next: edit the text a page shows, or a PDF/UA report to make an accessible file from the start.

Crop pages

You’ll crop half an inch from each side of every page. Use it to trim the white border of a scan, to cut printer’s marks off a proof, or to make slides fit a phone’s screen.

The margins are measured on the page as a reader sees it. A page turned on its side loses the same strip from its visible top as an upright page does, so one set of margins suits a document of mixed sizes and rotations. The program prints each page whose crop hides content:

packages/sdk/examples/crop-pages.ts
// Crop every page by half an inch on each side, whatever its size or rotation.
//
// Margins are measured on the page as it shows, so a page turned on its side loses the same
// strip from its visible top as an upright one. Cropping only hides content: the edit lists the
// pages whose hidden content stays in the file, where text extraction still finds it.
import { Document } from "@laminapdf/sdk";
/** The document with 36 points cropped from each side of every page. Needs `init()`. */
export function cropPages(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const pages = doc.pages.map((page) => page.id);
const edited = doc.cropPages(pages, { top: 36, right: 36, bottom: 36, left: 36 });
for (const page of edited.croppedContentRemains ?? []) {
console.warn(`page ${page} hides content that is still in the file`);
}
return doc.save();
}
Page 1 of crop_pages.pdf
Open crop_pages.pdf (4 pages, 3 KB)

The input has four pages, one at each rotation, and the second is drawn at twice the usual scale. In the result, each page shows 72 points less across and 72 less down, and its “Page n” label sits the same distance from its visible corner.

  • cropPages (CropPages in Rust) sets each page’s crop box: the part of the page a reader shows and prints. It takes top, right, bottom and left in points, and a side you leave out is 0.
  • Cropping hides content but keeps it. Text outside the crop box stays in the file, and copying or extracting text still finds it. The edit’s croppedContentRemains lists the pages where that is true.
  • Signed forms: cropping a page that shows a signed field breaks the signature, so saving refuses the edit unless you allow the save to break it.
  • Undo: one undo() puts every page’s crop box back.
  • Set a box exactly: setPageBoxes (SetPageBoxes in Rust) writes any of a page’s five boxes in the page’s own coordinates: media (the paper), crop, bleed, trim and art. null removes a box, so the page uses its default, which is the media box for the crop box and the crop box for the others. Each box must lie inside the media box.
  • Crop only some pages: pass their IDs. To give pages different margins, crop each group in its own call inside one transact, and one undo reverts them all.
  • Private content: a crop isn’t a redaction. Anyone with another tool can read what it hides, so don’t crop a page to remove something private.

Next: organise pages, to delete, move and rotate them too.

Resize pages

You’ll put every page of a document on Letter paper, scaling each page’s content to fit. Use it to print a document made on A4 in North America, to make a mixed stack of scans one size, or to give slides the same paper as the report they go in.

A page keeps its proportions. An A4 page is a little taller and narrower than Letter, so it is scaled down to Letter’s height and centred, with a thin margin on each side:

packages/sdk/examples/resize-pages.ts
// Make every page Letter, scaling each page's content to fit.
//
// A page keeps its proportions: an A4 page is scaled down to Letter's height and centred, with
// a little room on each side. The bookmarks, links and named places that point into a page move
// with its content, so they still land on the same words.
import { Document } from "@laminapdf/sdk";
/** Letter, in points. */
const LETTER = { width: 612, height: 792 };
/** The document with every page on Letter paper, its content scaled to fit. Needs `init()`. */
export function resizePages(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const pages = doc.pages.map((page) => page.id);
doc.resizePages(pages, LETTER);
return doc.save();
}
Page 1 of resize_pages.pdf
Open resize_pages.pdf (2 pages, 5 KB)

The input has an A4 page and a Letter page. In the result both are Letter. The first page’s text is a little smaller and its highlight still covers the same words, and the second page is as it was.

  • resizePages (ResizePages in Rust) takes the new paper’s width and height in points. The size is the paper’s before any rotation, so a page turned on its side stays turned.
  • The page’s content moves as one piece, and everything that points into the page moves with it. That covers links, notes, highlights and form fields, bookmarks and named places, the view the document opens at, and the boxes a screen reader uses to find a figure. A bookmark that showed a paragraph at the top of the window still does.
  • The page shows its whole new paper: a crop box goes, and the bleed, trim and art boxes move with the content.
  • Undo: one undo() puts every page back.
  • Keep the content’s size: pass { mode: "extend", anchor: "topLeft" } (ResizePages::extend in Rust). The paper grows around the content, or is cut down to the part of it the new paper covers. The anchor says where the old page sits: "center" by default, or a corner or an edge.
  • Turn pages to portrait or landscape: setOrientation(ids, "landscape") turns each page shown the other way a quarter turn clockwise, and leaves the rest alone. It turns the page as readers show it (/Rotate). For a printer or tool that ignores that, pass "swapBox": the paper’s sides swap and the content, annotations and bookmarks turn into it.
  • Signed forms: resizing or turning a page that shows a signed field breaks the signature, so saving refuses the edit unless you allow the save to break it.
  • Files a resize refuses: to move a page’s content, Lamina PDF reads it. A page whose content Lamina PDF can’t decode is refused with unsupported-filter, and the document is left as it was.

Next: crop pages, to hide part of a page instead.

Copy pages between PDFs

You’ll copy a page from one PDF into another, then make a new PDF from three pages of a longer one. Use the first to add a cover page, an appendix or a signed form from another file, and the second to send someone only the chapter they need.

Add the other file as a source first. Lamina PDF names the source by a hash of its bytes and lists its page IDs, and you pick the pages to copy from that list. The program copies the other file’s third page to the end:

packages/sdk/examples/insert-pages.ts
// Copy a page from another PDF into this one.
//
// The copy keeps its annotations and form fields. A field whose name the document already uses
// takes the next free `<name>#2`, and a link to a page that didn't come along is removed; the
// edit lists both.
import { Document } from "@laminapdf/sdk";
/** `bytes` with the third page of `other` added at the end. Needs `init()`. */
export function insertPages(bytes: Uint8Array, other: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const source = doc.addSource(other);
const third = source.pages[2];
if (third === undefined) {
throw new Error("the other file has no third page");
}
const edited = doc.insertPagesFrom(source.id, [third], "end");
for (const field of edited.fields ?? []) {
if (field.outcome === "renamed") {
console.warn(`a copied field was renamed ${field.name}`);
}
}
console.warn(`${edited.linksRemoved?.length ?? 0} links removed`);
return doc.save();
}
Page 1 of insert_pages.pdf
Open insert_pages.pdf (3 pages, 4 KB)

The result has three pages, and the third is the copied one. Its text field was called name, which the form already used, so the copy’s field is name#2 and keeps a value of its own.

extractPages (extract_pages in Rust) takes page IDs and returns a new document holding only those pages:

packages/sdk/examples/extract-pages.ts
// Make a new PDF from some pages of another.
//
// The new file holds only what its pages use, and its pages keep the labels they had (`iii`,
// `1`, `2` rather than 1, 2, 3).
import { Document } from "@laminapdf/sdk";
/** A new document of the third to the fifth page of `bytes`. Needs `init()`. */
export function extractPages(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
const pages = doc.pages.slice(2, 5).map((page) => page.id);
using part = doc.extractPages(pages);
return part.save();
}
Page 1 of extract_pages.pdf
Open extract_pages.pdf (3 pages, 912 bytes)

The new file’s pages keep the labels they showed in the book, iii, 1 and 2, and it holds only the fonts and images those pages use.

  • A copy is a new page with a new ID, listed in the edit’s pageOrder. The copy shares nothing with the source file, so changing one never changes the other.
  • The copy’s annotations come along. A link to a page that came too still works; a link to a page left behind is removed, and the edit’s linksRemoved lists the page that held it.
  • Form fields keep their names. A name the document already uses gets the next free number, <name>#2 and on, and the edit’s fields lists each renamed field.
  • A signature’s field isn’t copied, since a signature signs one place in one file. The edit’s fields lists it as notCopied.
  • Page labels continue the numbering where the copies land, and every other page keeps its label.
  • Replace a page: replacePages(targets, source, pages) puts each source page in a target’s place. Bookmarks, links and named destinations that pointed at the old page point at the new one.
  • Keep fields linked: pass { fields: "link" } as the last argument, and a copied field joins the document’s field of the same name, so both show one value. Linking needs both fields to have the same type and value; otherwise the copy is renamed.
  • Leave annotations behind: pass { annotations: false } to copy only the page content and its form fields.
  • Split into several files: exportRanges([[a, b], [c]]) makes one document per list of pages, and split cuts a file by chapter or page count.
  • Tagged documents: a copied page keeps its tags when the document is tagged: the elements that hold its content join the document’s structure tree, so a screen reader still reads it in order. A role, class or element ID the document already uses another way is renamed <name>#2, and the edit’s structureRenamed lists it. Copied into an untagged document, the page comes without its tags, and the edit’s tagsDropped lists it. On a file that claims PDF/UA-1, copying from a file without that claim warns with imported-pdfua-unchecked.
  • Undo: one undo() removes every copied page and what came with it.

Next: duplicate pages, to copy a page within the same document.

Merge and split PDFs

You’ll merge two PDFs into one, then split a book into one file per chapter. Use the first to send a report with its appendices as one file, and the second to send each reader only the chapter they need.

Document.merge (Document::merge in Rust) takes each file’s bytes and a name for it, and returns a new document with every file’s pages in order:

packages/sdk/examples/merge-documents.ts
// Merge PDFs into one, with a bookmark for each file.
//
// Each file's own bookmarks go under a bookmark named after it, its form fields keep working
// (renamed when two files use one name), and its pages keep their labels.
import { Document } from "@laminapdf/sdk";
/** One document of `files` (each a name and its bytes), in order, with a bookmark per file. Needs `init()`. */
export function mergeDocuments(files: readonly (readonly [string, Uint8Array])[]): Uint8Array<ArrayBuffer> {
using merged = Document.merge(files.map(([title, bytes]) => ({ bytes, title })));
return merged.save();
}
Page 1 of merge_documents.pdf
Open merge_documents.pdf (6 pages, 2 KB)

The merged file has six pages: the five of references.pdf, then the one of hello.pdf. Its bookmarks start with one per file, named as you named the file, and references.pdf’s own bookmarks sit under its bookmark.

split cuts a document where each top-level bookmark’s page begins and returns one new document per chapter:

packages/sdk/examples/split-document.ts
// Split a PDF into one file per chapter.
//
// The file is cut where each top-level bookmark's page begins, and each part keeps the
// bookmarks of its chapter.
import { Document } from "@laminapdf/sdk";
/** One file per chapter of `bytes`: a part from each top-level bookmark's page to the next. Needs `init()`. */
export function splitDocument(bytes: Uint8Array): Uint8Array<ArrayBuffer>[] {
using doc = Document.open(bytes);
const chapters = doc.split({ bookmarks: 1 });
try {
return chapters.map((chapter) => chapter.save());
} finally {
for (const chapter of chapters) chapter.free();
}
}

The book has three chapters of four pages, so the program makes three files. Each keeps its chapter’s bookmark and the two section bookmarks under it.

  • Each file’s pages come in as copied pages do: with their annotations, form fields and page labels, and with the named destinations their links use. Copy pages between PDFs explains the rules.
  • When two files use one form field name, the later file’s field becomes <name>#2. A named destination that two files use is renamed the same way, and the bookmarks and links that used it follow the new name.
  • Layers keep the visibility each file gave them.
  • A merged file is a new document, so saving it writes a whole file with no password. An encrypted file needs its password beside its bytes.
  • A part of a split holds only what its pages use, as a document from extractPages does.

Merged pages keep their tags when the result can stay tagged throughout: when you merge into a tagged document, or make a new document from files that are all tagged. Each file’s elements go under a Part element named after it, so a screen reader reads the files in order. When one of the files is untagged, a new document comes out untagged, since a tagged file must tag all its content.

On a document that claims PDF/UA-1, merging a file without that claim warns with imported-pdfua-unchecked. A document that claims a PDF/A level warns with imported-pdfa-unchecked when a merged file doesn’t claim the same level, so check the saved file with a PDF/A validator.

  • Keep the files’ bookmarks at the top level: pass { outline: "keep" } as the options. { outline: "none" } leaves them out.
  • Merge into an open document: add each file with addSource, then call doc.mergeDocuments([a.id, b.id], "end"). The edit’s renamedDestinations lists each renamed destination, and one undo() takes the whole merge back.
  • Merge only some pages: pass { source: a.id, pages: [...] } in place of the source’s ID. Bookmarks to pages left behind are dropped, and the edit’s bookmarksDropped counts them.
  • Split by page count: split({ count: 10 }) makes parts of ten pages. split({ ranges: [[a, b], [c]] }) makes one part per list of page IDs.
  • Split at sections: split({ bookmarks: 2 }) cuts at the second level of bookmarks.

Next: organise pages, to put the merged pages in the order you want.

Extract text for an LLM

The Extract text and Markdown guide explains each output and its options. Here you’ll turn a PDF into three outputs an LLM or a search index can use: Markdown in reading order, JSON giving every paragraph and table its page and box, and 400-token chunks.

In TypeScript the function returns the three outputs and needs the extract module, init({ extract: true }). In Rust, the program instead extracts once and writes the three files. Both give the same JSON:

packages/sdk/examples/extract-markdown.ts
// Extract a PDF's text for an LLM: Markdown in reading order, JSON with a box for every block,
// and chunks sized for retrieval.
//
// Tables drawn with lines come out as Markdown tables, and text a reader can't see (white,
// invisible or off the page) is left out of all three.
import { type Chunk, Document, type Extraction } from "@laminapdf/sdk";
/** What a PDF gives an LLM or a search index. */
export interface ForAnLlm {
/** The text in reading order, with a `<!-- page N -->` comment before each page. */
readonly markdown: string;
/** Every block with its page and box, the text left out, the file's warnings and the chunks. */
readonly json: Extraction;
/** About 400 tokens each, a new one at each heading. */
readonly chunks: readonly Chunk[];
}
/** The Markdown, the JSON and the chunks of `bytes`. Needs `init({ extract: true })`. */
export function extractForAnLlm(bytes: Uint8Array): ForAnLlm {
using doc = Document.open(bytes);
// Page markers let a reader cite the page a passage came from.
const markdown = doc.extract({ format: "markdown", pageMarkers: true });
// The JSON carries the same chunks, and each block's place in the Markdown.
const json = doc.extract({ format: "json", pageMarkers: true, chunk: { maxTokens: 400 } });
return { markdown, json, chunks: json.chunks ?? [] };
}

Run the Rust program on any PDF: cargo run -p laminapdf --example extract_markdown -- report.pdf out.

Text runsfrom every pageLinesruns joinedBlocksparagraphs, tablesReading ordertags, else columnsSet asideinto droppedinvisible · off-page · tiny · clippedlow-contrast · covered · artifactrunning-header · running-footerpage-numberMarkdownJSONlaminapdf.extract/1ChunksText runsfrom every pageSet asideinto droppedinvisibleoff-pagetinyclippedlow-contrastcoveredartifactrunning-headerrunning-footerpage-numberLinesruns joinedBlocksparagraphs, tablesReading ordertags, else columnsMarkdownJSONlaminapdf.extract/1Chunks
Extraction joins a page's text runs into lines and blocks, orders them, then writes Markdown, JSON and chunks.
12345671: the title, across both columns2–4: down the left column5–7: then down the right column12345671: the title, across both columns2–4: down the left column5–7: then down the right column
On a two-column page, a title across both columns comes first, then the left column, then the right.
  • extract (doc.extract in TypeScript) reads every page’s text, joins it into lines and paragraphs, and puts the paragraphs in reading order. A two-column page reads down the left column, then the right; a title across both columns comes first.
  • Each block has a confidence from 0 to 1. When the page’s columns could be read in more than one order, the page raises the extract-column-order-uncertain warning and the blocks in doubt get a confidence of 0.5. A pipeline can check those pages or send them to a layout model.
  • Tables drawn with lines become table blocks with their cells, and Markdown writes them as tables. A cell that spans columns or rows makes the table HTML, since Markdown tables can’t span.
  • A table that goes on over a page break comes out as one table in the Markdown, the text and the chunks, with its header once. The JSON keeps one block per page, linked by continuedBy and continues, so each block’s box stays on its own page.
  • Text a reader can’t see never reaches the outputs: invisible text (such as the hidden layer of a scanned page), text off the page or too small to read, and text cut away by a clipping path. Nor does near-white text with nothing behind it, or text painted over by a later shape, image or comment. Headers, footers and page numbers that repeat across pages, and text the file marks as an artifact, are left out too. The JSON lists each such run under dropped, with the reason and how many characters it held.
  • to_markdown (format: "markdown" in TypeScript) writes headings, paragraphs and tables, with a <!-- page N --> comment before each page, so a passage can be traced to its page.
  • chunks (format: "chunks", or the chunk option with the JSON) groups whole paragraphs and tables up to the budget, starting a new chunk at each heading. Each chunk records the blocks, pages and boxes it came from, and where its text sits in the Markdown.
  • extract_json (format: "json") writes the laminapdf.extract/1 document: the pages, every block with its box in points from the top-left corner, the dropped text, the file’s warnings and the chunks.
  • Only some pages: pages: [0, 1] in TypeScript, ExtractOptions::new().with_pages(vec![0, 1]) in Rust (page indexes start at 0).
  • Tables without lines: tables: "lattice-and-stream" (.with_tables(TableMode::LatticeAndStream)) also looks for text lined up in columns. It finds more tables, and now and then a pair of columns that isn’t one.
  • Bigger or smaller chunks: change maxTokens (with_max_tokens). A token here is about four characters, a rough count that runs low for code, numbers and scripts other than Latin, so leave room.
  • Overlap between chunks: overlap: 80 (.with_overlap(80)) repeats up to about 80 tokens of whole paragraphs from the end of the previous chunk.
  • One output (TypeScript): set format to "markdown", "text", "json" or "chunks".
  • Pages that need OCR: a scanned page has no text to extract, so its Markdown is empty. Each page in the JSON has a textLayer whose status says so: pages.filter(p => p.textLayer.status === "needs-ocr") in TypeScript, extraction.pages.iter().filter(|p| p.text_layer.status == TextLayerStatus::NeedsOcr) in Rust. Send those pages to OCR or a vision model. A page made searchable by OCR is ocr-layer, since extraction leaves its invisible text out; the file’s warnings name both kinds.
  • When the text looks wrong: Troubleshooting text extraction starts from what you see, such as columns read across or characters that come out as �.
  • A long file in steps (Rust): doc.extract_job(&options) and step do a page per unit of work, so a long file can report progress or stop between steps.

Benchmarks has extraction’s scores on a public benchmark and how many pages a second it reads.

Next: all recipes.

A PDF/UA report

You’ll build a one-page sales report that a screen reader can follow: headings, a table, a chart described in words and a link. You need this when a document has to meet accessibility law or a client’s accessibility policy.

The function turns on the PDF/UA-1 profile, then draws each part of the report inside a tag that says what it is: a heading, a table cell, a figure. In TypeScript it needs the text module, init({ text: true }). Both languages write the same bytes:

packages/sdk/examples/pdf-ua-report.ts
// An accessible report that screen readers can follow, checked against PDF/UA-1 when it is built.
import { Builder, Font, type Surface, type Tag, type TagName } from "@laminapdf/sdk";
const MARGIN = 56;
const ROW = 18;
const COLUMN = 144;
const HEADER_BASELINE = 40;
const TITLE_BASELINE = 90;
const TABLE_TOP = 150;
const LINK_BASELINE = 400;
const CHART_LEFT = 320;
const CHART_BASE = 360;
const BAR_WIDTH = 36;
const BAR_PITCH = 50;
const BODY = 11;
/** The font sizes of the title and the headings; other text is `BODY`. */
const SIZES: Partial<Record<TagName, number>> = { H1: 22, H2: 15 };
const BLUE = [0.12, 0.47, 0.78] as const;
const QUARTERS = [
["Q1", 120],
["Q2", 135],
["Q3", 160],
["Q4", 150],
] as const;
const CHART_ALT = "Bar chart of sales by quarter: 120, 135, 160 and 150 thousand euros.";
/**
* The report's bytes. Needs `init({ text: true })`.
*
* @param notoSans - the bytes of the Noto Sans font file.
*/
export function pdfUaReport(notoSans: Uint8Array): Uint8Array<ArrayBuffer> {
using b = new Builder({ profiles: ["PDF/UA-1"] });
b.metadata({ title: "Annual sales report 2026" });
b.lang("en-GB");
const font = Font.fromBytes(notoSans);
b.font(font);
const page = b.page("A4");
draw(page.surface(), font);
page.finish();
using doc = b.finish();
return doc.save();
}
/** One line of text with its baseline at `y`, as the structure element `tag`, sized by it. */
function line(s: Surface, font: Font, tag: Tag, text: string, x: number, y: number): void {
const size = (typeof tag === "string" ? SIZES[tag] : undefined) ?? BODY;
s.tag(tag, (s) => s.text(text, { font, size, at: [x, y] }));
}
function draw(s: Surface, font: Font): void {
// The running header is decoration: an artifact, which screen readers skip.
s.artifact("pagination", (s) => s.text("Acme Widgets", { font, size: BODY, at: [MARGIN, HEADER_BASELINE] }));
line(s, font, "H1", "Annual sales report 2026", MARGIN, TITLE_BASELINE);
line(s, font, "P", "Sales grew in three quarters of four.", MARGIN, TITLE_BASELINE + 2 * ROW);
table(s, font);
chart(s);
const link = {
target: { type: "uri", uri: "https://example.com/accounts" },
contents: "The full 2026 accounts",
} as const;
s.tag("P", (s) =>
s.text("The full accounts", { font, size: BODY, at: [MARGIN, LINK_BASELINE], fill: [...BLUE], link }),
);
}
/** A heading and a table of the quarters, whose first row holds the columns' header cells. */
function table(s: Surface, font: Font): void {
line(s, font, "H2", "Sales by quarter", MARGIN, TABLE_TOP);
const header: Tag = { type: "TH", scope: "column" };
s.tag("Table", (s) => {
s.tag("TR", (s) => {
line(s, font, header, "Quarter", MARGIN, TABLE_TOP + ROW);
line(s, font, header, "Sales (k€)", MARGIN + COLUMN, TABLE_TOP + ROW);
});
QUARTERS.forEach(([quarter, sales], i) => {
const y = TABLE_TOP + ROW * (i + 2);
s.tag("TR", (s) => {
line(s, font, "TD", quarter, MARGIN, y);
line(s, font, "TD", sales.toFixed(0), MARGIN + COLUMN, y);
});
});
});
}
/** The quarters as bars standing on the chart's base: one figure with alternate text. */
function chart(s: Surface): void {
s.tag({ type: "Figure", alt: CHART_ALT }, (s) => {
s.fillColor([...BLUE]);
QUARTERS.forEach(([, sales], i) => {
s.path((p) => p.rect([CHART_LEFT + BAR_PITCH * i, CHART_BASE - sales, BAR_WIDTH, sales])).fill();
});
});
}
Page 1 of pdf_ua_report.pdf
Open pdf_ua_report.pdf (1 page, 10 KB)

The result is one A4 page that reads, in order, as a title, a summary, a table of four quarters, a bar chart and a link. The Result tab shows it, with a link to the PDF.

  • profiles: ["PDF/UA-1"] (Profile::PdfUa1 in Rust) tags the document and makes finish() check the rules a program can check. It fails with a coded error for the first rule the report breaks; Accessible PDFs lists them.
  • metadata gives the report its title and lang its language, which PDF/UA-1 asks for. The font is an embedded Noto Sans, because PDF/UA-1 refuses the standard 14 fonts.
  • tag puts what its callback draws inside a structure element, such as H1, P or TD, in reading order. The line helper tags one line of text and sizes it by its tag: 22 points for H1, 15 for H2, 11 for the rest.
  • The table’s first row holds TH header cells with a column scope, so a screen reader can name each cell’s column.
  • The four bars are one Figure with alternate text, the sentence a screen reader reads in place of the drawing. The running header is an artifact, which screen readers skip.
  • The link’s contents, “The full 2026 accounts”, is its description. The builder makes the link a Link element inside its paragraph.
  • The numbers: change QUARTERS, then change CHART_ALT to match. The builder checks that the chart has alternate text, not that the text is right; see What a program can’t check.
  • A list: nest an "L", an "LI" for each item, and inside each a "Lbl" for the bullet and an "LBody" for the text. An L holds LI items or a nested L, and an LI holds a Lbl and an LBody: anything else inside them fails finish() with invalid-structure-nesting.
  • A passage in another language: tag it with its own, as in { type: "P", lang: "fr-FR" } (Tag::new(TagKind::P).with_lang("fr-FR") in Rust).
  • Accessible and archival at once: add a PDF/A profile beside it, as in profiles: ["PDF/A-2u", "PDF/UA-1"]. The PDF/A archive does this.

Next: a PDF/A archive, a letter written for long-term keeping.

A PDF/A archive

You’ll write a letter confirming an order as a PDF/A file, which looks the same in any viewer for decades. You need it for documents kept for years, often by law: contracts, records, letters to customers. The recipe writes the letter twice, at two PDF/A levels.

The function takes the level, 2b or 2u, and builds the same letter under that level’s profiles. In TypeScript it needs the text module, init({ text: true }). Both languages write the same bytes:

packages/sdk/examples/pdf-a-archive.ts
// An archival letter, written as PDF/A-2b and as PDF/A-2u that is also PDF/UA-1.
import { Builder, Font, Image, PAGE_SIZES, type Profile, type Surface } from "@laminapdf/sdk";
const MARGIN = 56;
const BAND_HEIGHT = 70;
const TITLE_BASELINE = 110;
/** The top of the letter's text and of the photo beside it, and the height of both. */
const BLOCK_TOP = 130;
const BLOCK_HEIGHT = 120;
const LETTER_WIDTH = 300;
const PHOTO_LEFT = 380;
const PHOTO_WIDTH = 160;
const FOOTER_BASELINE = 300;
const TITLE = 22;
const BODY = 11;
const BAND_OPACITY = 0.35;
const PHOTO_ALT = "A photograph of the sprockets, packed in a box";
const LETTER =
"Thank you for your order of 12 sprockets. This letter confirms the delivery date and the price we agreed. " +
"Keep it: PDF/A files look the same in any viewer, now and in the future.";
/** PDF/A-2b, or PDF/A-2u (whose text maps to Unicode) with PDF/UA-1. */
const PROFILES: Record<"2b" | "2u", Profile[]> = {
"2b": ["PDF/A-2b"],
"2u": ["PDF/A-2u", "PDF/UA-1"],
};
/**
* The letter's bytes. Needs `init({ text: true })`.
*
* @param level - `2b` or `2u`.
* @param notoSans - the bytes of the Noto Sans font file.
* @param photo - the bytes of a JPEG photo.
*/
export function pdfAArchive(level: "2b" | "2u", notoSans: Uint8Array, photo: Uint8Array): Uint8Array<ArrayBuffer> {
using b = new Builder({ profiles: PROFILES[level], tagged: true });
b.metadata({ title: "Order confirmation 42", author: "Acme Widgets Ltd" });
b.lang("en-GB");
const font = Font.fromBytes(notoSans);
b.font(font);
const page = b.page("A4");
draw(page.surface(), font, Image.jpeg(photo));
page.finish();
using doc = b.finish();
return doc.save();
}
function draw(s: Surface, font: Font, photo: Image): void {
// A translucent band across the top: decoration, and transparency, which PDF/A-2 allows.
const [width] = PAGE_SIZES.A4;
s.artifact("layout", (s) => {
s.save().opacity(BAND_OPACITY, 1).fillColor([0.12, 0.47, 0.78]);
s.path((p) => p.rect([0, 0, width, BAND_HEIGHT])).fill();
s.restore();
});
s.tag("H1", (s) => s.text("Order confirmation 42", { font, size: TITLE, at: [MARGIN, TITLE_BASELINE] }));
s.tag("P", (s) => s.textBox(LETTER, { font, size: BODY, box: [MARGIN, BLOCK_TOP, LETTER_WIDTH, BLOCK_HEIGHT] }));
s.image(photo, [PHOTO_LEFT, BLOCK_TOP, PHOTO_WIDTH, BLOCK_HEIGHT], PHOTO_ALT);
s.tag("P", (s) =>
s.text("Acme Widgets Ltd, 1 Example Street, London", { font, size: BODY, at: [MARGIN, FOOTER_BASELINE] }),
);
}

The result is one A4 letter under a translucent blue band, with a photo beside its text: the Result tab shows both versions, PDF/A-2b and PDF/A-2u, with links to the PDFs.

  • PDF/A-2b makes the letter look the same everywhere. PDF/A-2u also maps every glyph to Unicode, so the text can be searched and copied. That copy is PDF/UA-1 too, so a screen reader can follow it.
  • PDF/A needs every font embedded, so the letter uses Noto Sans rather than one of the standard 14 fonts. finish() checks rules like this one and fails with a coded error for the first one the letter breaks.
  • The builder writes what PDF/A asks for: the PDF/A identification in the file’s XMP metadata, and an sRGB output intent that says what its RGB colours mean. See What PDF/A asks for.
  • Both copies draw the same tagged content: an H1 title, P paragraphs and the photo as a figure with alternate text. PDF/A-2b doesn’t ask for tags, but PDF/UA-1 does.
  • The blue band is drawn at 35% opacity, as a layout artifact that screen readers skip. PDF/A-2 allows transparency.
  • textBox breaks the letter into lines inside its box, beside the photo. The JPEG goes into the file as it is.
  • The letter: change LETTER. textBox leaves out lines that don’t fit, so make BLOCK_HEIGHT larger for a longer letter, or pass overflow: "error" to fail with text-overflow instead.
  • The photo: pass any RGB or gray JPEG, or Image.png(bytes) for a PNG (Image::png in Rust). A CMYK JPEG fails finish() with device-color-without-output-intent, because the output intent is sRGB.
  • Other profiles: pass the ones you need, such as ["PDF/A-2u"] alone or ["PDF/A-2b", "PDF/UA-1"]. A document can claim PDF/UA-1 and at most one PDF/A profile.
  • An attached file: PDF/A-2 refuses attachments, so switch to PDF/A-3b, as the PDF/A-3 invoice does.

Next: a PDF/A-3 invoice with XML, with its data attached for software to read.

A PDF/A-3 invoice with XML

You’ll write a one-page invoice as PDF/A-3b, with the same invoice attached as XML. You need this for e-invoices such as Factur-X and ZUGFeRD, where a person reads the PDF and the buyer’s software reads the XML.

The function draws the invoice, writes the same items as XML and attaches that file before it finishes. In TypeScript it needs the text module, init({ text: true }). Both languages write the same bytes:

packages/sdk/examples/pdf-a3-invoice-with-xml.ts
// A PDF/A-3b invoice that carries the same invoice as XML, attached for software to read.
import { Builder, Font, PAGE_SIZES, type Surface } from "@laminapdf/sdk";
const MARGIN = 56;
/** The page's right edge, less the margin: where the rule under the items ends. */
const RIGHT = PAGE_SIZES.A4[0] - MARGIN;
const AMOUNTS = 460;
const ROW = 22;
const TITLE_BASELINE = 80;
const FIRST_ROW = 130;
/**
* How far above the next row's baseline the rule sits, and how far below it the total and
* the note are.
*/
const RULE_RISE = 7;
const TOTAL_DROP = 18;
const NOTE_DROP = 68;
/** How far left of the amounts column the total starts, to fit its "Total" label. */
const TOTAL_INDENT = 40;
const TITLE = 24;
const TOTAL = 14;
const BODY = 11;
const ITEMS = [
["Sprockets", 12, 1.25],
["Gadget", 1, 79.9],
["Delivery", 1, 4.5],
] as const;
/** The invoice's total. */
function total(): number {
return ITEMS.reduce((sum, [, qty, price]) => sum + qty * price, 0);
}
/** The invoice as XML, in a made-up schema (a real e-invoice follows EN 16931, as Factur-X does). */
function invoiceXml(): string {
const lines = ITEMS.map(
([item, qty, price]) => ` <line item="${item}" quantity="${qty}" price="${price.toFixed(2)}"/>\n`,
);
return `<?xml version="1.0" encoding="UTF-8"?>\n<invoice number="42" currency="EUR">\n${lines.join("")} <total>${total().toFixed(2)}</total>\n</invoice>\n`;
}
/**
* The invoice's bytes. Needs `init({ text: true })`.
*
* @param notoSans - the bytes of the Noto Sans font file.
*/
export function pdfA3InvoiceWithXml(notoSans: Uint8Array): Uint8Array<ArrayBuffer> {
using b = new Builder({ profiles: ["PDF/A-3b"] });
b.metadata({ title: "Invoice 42", author: "Acme Widgets Ltd" });
const font = Font.fromBytes(notoSans);
b.font(font);
const page = b.page("A4");
draw(page.surface(), font);
page.finish();
b.attach("invoice-42.xml", new TextEncoder().encode(invoiceXml()), "text/xml", {
relationship: "alternative",
description: "Invoice 42 as XML",
});
using doc = b.finish();
return doc.save();
}
function draw(s: Surface, font: Font): void {
s.text("Invoice 42", { font, size: TITLE, at: [MARGIN, TITLE_BASELINE] });
let y = FIRST_ROW;
for (const [item, qty, price] of ITEMS) {
s.text(`${qty} × ${item}`, { font, size: BODY, at: [MARGIN, y] });
s.text(`€ ${(qty * price).toFixed(2)}`, { font, size: BODY, at: [AMOUNTS, y] });
y += ROW;
}
const rule = y - RULE_RISE;
s.strokeColor([0.5])
.path((p) => p.moveTo(MARGIN, rule).lineTo(RIGHT, rule))
.stroke();
s.text(`Total € ${total().toFixed(2)}`, { font, size: TOTAL, at: [AMOUNTS - TOTAL_INDENT, y + TOTAL_DROP] });
s.text("The invoice is attached as invoice-42.xml.", {
font,
size: BODY,
at: [MARGIN, y + NOTE_DROP],
link: { target: { type: "uri", uri: "https://example.com/invoices/42" }, contents: "Invoice 42 online" },
});
}

The result is one A4 page with three line items and a total of € 99.40, carrying invoice-42.xml. The Result tab shows it, with a link to the PDF. Viewers that show attachments list it there.

  • profiles: ["PDF/A-3b"] (Profile::PdfA3b in Rust) asks for PDF/A-2b’s rules and allows attached files of any kind. finish() fails with a coded error for the first rule the invoice breaks; see Archival PDFs.
  • PDF/A needs every font embedded, so the invoice uses Noto Sans rather than one of the standard 14 fonts.
  • invoiceXml writes the line items and the total from the same ITEMS the page draws, so the PDF and the XML always agree. Its schema is made up for the recipe.
  • attach adds the file with its name, its bytes and its MIME type, text/xml. PDF/A needs a MIME type on every attachment, or finish() fails with embedded-file-without-mime-type.
  • relationship: "alternative" (AfRelationship::Alternative) says the XML is another form of the same content, and the builder associates it with the document. description is the text a viewer shows beside the file.
  • The items: change ITEMS. The page, the total and the XML all follow.
  • A real e-invoice: replace invoiceXml with XML that follows EN 16931, the European e-invoicing standard, as Factur-X and ZUGFeRD do. Those formats also need XMP entries of their own: Make an invoice Factur-X adds them, with the XML, to the finished file.
  • Other attachments: attach the file the invoice was made from with relationship: "source", or the data behind it with "data" (AfRelationship::Source, AfRelationship::Data). Each needs its own name and MIME type.
  • Accessible too: add "PDF/UA-1" to profiles, set lang and tag the content, as the PDF/UA report does.

Next: make an invoice Factur-X, the same invoice with its Factur-X XML and metadata.

Make an invoice Factur-X

You’ll turn a PDF/A-3 invoice into a Factur-X one: the same file, carrying the invoice’s data as XML for the buyer’s software to read. You need this for e-invoicing in France and Germany, where Factur-X and ZUGFeRD are one format.

The function opens the invoice, attaches factur-x.xml as the document’s alternative form, records the four Factur-X properties in the XMP metadata, and saves:

packages/sdk/examples/attach-factur-x.ts
// Make a PDF/A-3 invoice a Factur-X (ZUGFeRD) one: attach its structured data as factur-x.xml,
// the document's alternative form, and record the Factur-X properties in the XMP metadata, which
// keeps the file valid PDF/A-3.
// The XML here is a placeholder: a real one is the invoice in the EN 16931 Cross Industry Invoice
// syntax, made by your invoicing system. The file must already be PDF/A-3.
import { Document } from "@laminapdf/sdk";
/** The Factur-X XMP namespace and prefix (Factur-X 1.0, §6.2.2). */
const FX = "urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0#";
/** A placeholder for the invoice's Cross Industry Invoice XML. */
const XML = `<?xml version="1.0" encoding="UTF-8"?>
<rsm:CrossIndustryInvoice xmlns:rsm="urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100">
<!-- The invoice's data, from your invoicing system. -->
</rsm:CrossIndustryInvoice>
`;
/**
* The invoice with factur-x.xml attached and the Factur-X properties recorded, saved incrementally.
*
* @param savedAt - the time of the save, as a PDF date (`D:20261110093000Z`) your app takes
* from its clock.
*/
export function attachFacturX(bytes: Uint8Array, savedAt: string): Uint8Array<ArrayBuffer> {
using doc = Document.open(bytes);
// PDF/A-3 asks every attached file for an association, a MIME type and a modification date.
const xml = doc.attachFileOp("factur-x.xml", new TextEncoder().encode(XML), "text/xml", {
attachTo: "document",
relationship: "alternative",
description: "Factur-X invoice",
modified: savedAt,
});
doc.transact((tx) => {
tx.apply({ op: "attachFile", args: xml });
const fx = (name: string, value: string) => tx.setXmpProperty(FX, "fx", name, { type: "text", value });
fx("DocumentType", "INVOICE");
fx("DocumentFileName", "factur-x.xml");
fx("Version", "1.0");
fx("ConformanceLevel", "MINIMUM");
});
// An attachment that breaks the file's PDF/A level says so before the save; this one keeps it.
for (const warning of doc.plan({ mode: "incremental", metadataDate: savedAt }).conformanceWarnings) {
console.warn(warning.code);
}
return doc.save({ mode: "incremental", metadataDate: savedAt });
}
Page 1 of attach_factur_x.pdf
Open attach_factur_x.pdf (1 page, 15 KB)

The result is the original bytes followed by one revision. It lists factur-x.xml beside the invoice’s own XML and still meets PDF/A-3b.

  • attachFileOp(name, bytes, mime, options) keeps the bytes for the session and makes the attachFile edit; attach_file does the same in Rust. attachFile applies it at once.
  • attachTo: "document" associates the file with the whole document, and relationship: "alternative" says it is another form of the same content. PDF/A-3 asks every attached file for an association, a MIME type and a modification date (modified), which your app takes from its clock.
  • Each file records its size, its dates and an MD5 checksum. Reading it back with attachmentBytes compares the checksum, so a file changed after it was attached shows as changed.
  • The fx: properties are not part of PDF/A, so Lamina PDF declares them in the metadata’s extension schema, as for any property of your own.
  • On a file that claims PDF/A-1 or PDF/A-2, plan() warns pdfa-attachment-forbidden: those levels allow no attached files but PDF/A ones.
  • The XML: replace the placeholder with the invoice in the EN 16931 Cross Industry Invoice syntax, from your invoicing system. Keep the name factur-x.xml; ZUGFeRD 1 files use ZUGFeRD-invoice.xml.
  • The profile: set ConformanceLevel to the profile your XML follows: MINIMUM, BASIC WL, BASIC, EN 16931 or EXTENDED.
  • A file that isn’t PDF/A-3 yet: make it with the builder, as A PDF/A-3 invoice with XML does. Converting another file to PDF/A is a separate job.

Next: Attachments, for reading, saving out and deleting attached files.

A 100-page report

You’ll make a 100-page report with two embedded fonts: on every page, a heading, a paragraph, a line of Chinese and a table of 20 products. Start from it for any long document you generate from data, such as monthly statements or a catalogue.

The function draws one region’s page at a time in a loop, then returns the PDF’s bytes:

packages/sdk/examples/report.ts
// A 100-page report with two embedded fonts. Each page has a heading, a paragraph broken into a
// box, a line of Chinese, a table of products with rules between the rows, and a page number.
import { Builder, type BuilderOptions, Font, PAGE_SIZES, type Rect, type Surface } from "@laminapdf/sdk";
/** The number of pages. */
const REPORT_PAGES = 100;
const PRODUCTS = 20;
const PRICE = 12.5;
const [PAGE_WIDTH] = PAGE_SIZES.A4;
const MARGIN = 56;
const RIGHT_EDGE = PAGE_WIDTH - MARGIN;
const HEADING_AT = [MARGIN, 72] as const;
const PARAGRAPH_BOX = [MARGIN, 88, RIGHT_EDGE - MARGIN, 60] as const;
const CHINESE_AT = [MARGIN, 166] as const;
const FOOTER_AT = [MARGIN, 800] as const;
const FIRST_ROW = 200;
const ROW_HEIGHT = 24;
/** The units' and the revenue's columns (left edge, width), both right-aligned. */
const UNITS_COLUMN = [300, 60] as const;
const REVENUE_COLUMN = [400, RIGHT_EDGE - 400] as const;
/** A cell's box starts this far above its row's baseline and is this tall; the rule is this far below. */
const CELL_RISE = 11;
const CELL_HEIGHT = 14;
const RULE_DROP = 7;
/** Font sizes: the heading, the paragraph and the Chinese line, the table, the page number. */
const SIZES = { heading: 20, body: 11, table: 10, footer: 9 } as const;
const PARAGRAPH =
"Quarterly figures for every region follow. Each table lists the units shipped, the revenue " +
"and the change against the previous quarter; totals are at the end of the report.";
/**
* The document's bytes. Needs `init({ text: true })`.
*
* @param latinFont - a font for the text, such as Noto Sans.
* @param chineseFont - a font with Chinese glyphs, such as Noto Sans SC.
* @param options - can fix the file ID, the producer and the creation date.
*/
export function report(
latinFont: Uint8Array,
chineseFont: Uint8Array,
options: BuilderOptions = {},
): Uint8Array<ArrayBuffer> {
using b = new Builder(options);
const font = Font.fromBytes(latinFont);
const chinese = Font.fromBytes(chineseFont);
b.font(font);
b.font(chinese);
for (let region = 1; region <= REPORT_PAGES; region++) {
const page = b.page("A4");
const s = page.surface();
s.text(`Region ${region}: quarterly report`, { font, size: SIZES.heading, at: HEADING_AT });
s.textBox(PARAGRAPH, { font, size: SIZES.body, box: PARAGRAPH_BOX });
s.text("你好世界,这是中文字体子集测试。", { font: chinese, size: SIZES.body, at: CHINESE_AT });
products(s, font, region);
s.text(`Page ${region} of ${REPORT_PAGES}`, { font, size: SIZES.footer, at: FOOTER_AT });
page.finish();
}
b.metadata({ title: "Quarterly report", author: "lamina examples" }).lang("en-GB");
using doc = b.finish();
return doc.save();
}
/** Made-up sales figures: the units of `product` that `region` shipped, from 0 to 499. */
function unitsShipped(region: number, product: number): number {
return (region * 37 + product * 11) % 500;
}
/** A region's table: one row per product, with its units and revenue right-aligned. */
function products(s: Surface, font: Font, region: number): void {
for (let product = 0; product < PRODUCTS; product++) {
const y = FIRST_ROW + ROW_HEIGHT * product;
const units = unitsShipped(region, product);
const size = SIZES.table;
s.text(`Product ${product + 1}`, { font, size, at: [MARGIN, y] });
s.textBox(String(units), { font, size, box: cell(UNITS_COLUMN, y), align: "end" });
s.textBox(`€ ${(units * PRICE).toFixed(2)}`, { font, size, box: cell(REVENUE_COLUMN, y), align: "end" });
s.strokeColor([0.8])
.path((p) => p.moveTo(MARGIN, y + RULE_DROP).lineTo(RIGHT_EDGE, y + RULE_DROP))
.stroke({ width: 0.5 });
}
}
/** The box of a cell in `column` (left edge, width) on the row at `baseline`. */
function cell([left, width]: readonly [number, number], baseline: number): Rect {
return [left, baseline - CELL_RISE, width, CELL_HEIGHT];
}

The result is 100 A4 pages, one per region. It has no reference PDF to open. Instead, Lamina PDF’s tests build and time the report in every JavaScript runtime and check its SHA-256 there, as does the Rust benchmark that builds the same bytes. Benchmarks has the timings.

  • It needs the text module, init({ text: true }), because it draws with embedded fonts.
  • Font.fromBytes reads each font file, and b.font registers both before the first page. Each font is embedded once for the whole report, with only the glyphs its 100 pages draw.
  • s.text draws one line, with at[1] as its baseline, and s.textBox breaks the paragraph into lines that fit PARAGRAPH_BOX.
  • In the table, the units and the revenue are text boxes as wide as their columns, with align: "end" to right-align them. cell works out each box from its column and the row’s baseline.
  • strokeColor([0.8]) sets a light gray, and each rule is a path from the left margin to the right edge, stroked 0.5 points wide.
  • metadata and lang("en-GB") set the title, author and language once for the document, and using frees the builder and the document when the function returns.
  • Your data: replace unitsShipped with your own figures, and set REPORT_PAGES and PRODUCTS to your counts.
  • A longer table: 20 rows end at 656 points, above the page number at 800. For more rows, lower ROW_HEIGHT or carry the rest over to the next page.
  • Another script: load a font that covers it and draw its text in that font, as the Chinese line does. See Text and fonts.
  • The file’s details: pass producer and creationDate in options, such as creationDate: "D:20261104120000Z". The builder never reads the clock, so a report without a date has none.

Next: open someone else’s file, with a password and tighter limits.

Open someone else's file

You’ll open a PDF from someone else, with a password if it needs one and tighter limits than the defaults, and get the outcome as a value. You need this wherever you accept uploads: a stranger’s file can be damaged, locked or built to use up memory.

The function opens the bytes under its limits and returns the page count and warning codes, or the error’s code and hint:

packages/sdk/examples/open-untrusted.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;
}
}

It writes no PDF. The value it returns is the result: { ok: true, pages, warnings } for a file that opened, or { ok: false, code, hint }, such as password-required for a locked file opened without its password.

  • It needs only init(): opening a file uses the base module, without fonts or text.
  • Document.open gets the password only when you pass one, and tries it against both of the file’s passwords. See Open password-protected files.
  • LIMITS allows 16 MiB decoded from one stream and 64 MiB in all, against defaults of 64 MiB and 1 GiB. A file that needs more fails with limit-exceeded, and every other limit keeps its default.
  • A file can open and still carry warnings: each one names a repair or a dropped value, and the function returns their codes.
  • isLaminaPdfError(e) picks out Lamina PDF’s coded errors, whose message and hint never contain text from the file. Any other error is a bug, so the function throws it again.
  • using frees the document as soon as the function returns, so the WebAssembly side keeps no copy of the file.
  • Ask for the password again: on password-required or wrong-password, ask your user and call openUntrusted again with their answer.
  • Name the limit: on limit-exceeded, return e.data?.limit too. It names the limit the file went over as Rust spells it, such as max_stream_decoded for maxStreamDecoded.
  • Other limits: add any limit from the table in Open files you don’t trust, such as a lower maxNestingDepth.
  • Refuse damaged files: add strict: true to the options, and a file that needs repair fails with strict instead of opening with warnings.

Next: save in a Web Worker, so a large file never freezes the page.

Save in a Web Worker

You’ll save a PDF in a Web Worker, reporting progress as it goes and stopping when the user presses Cancel. You need this in a browser app once files get large, because a save on the main thread freezes the page until it ends.

saveInWorker starts a Web Worker, opens the bytes there and saves them as a full rewrite, handing your onProgress and signal to each call:

packages/sdk/examples/worker-client.ts
// Saving a PDF in a Web Worker, so a large file never blocks the page: `@laminapdf/sdk/worker`
// runs the same API there, and each method returns a Promise. The save reports its progress step
// by step, and aborting the signal (a Cancel button, say) stops the work.
import { type CallOptions, connect } from "@laminapdf/sdk/worker";
/** What the save reports to and listens to. */
export type SaveInWorkerOptions = Pick<CallOptions, "onProgress" | "signal">;
/**
* Opens `bytes` in a Web Worker and saves them there as a full rewrite.
*
* @param bytes - any PDF; it is copied to the worker (`transfer: true` would move it).
* @param options - `onProgress` is called after each step of the save. Aborting `signal` stops
* the work wherever it is (starting the Web Worker, opening, or at the save's next step), and
* the promise rejects with a `cancelled` error.
* @returns the saved file.
*/
export async function saveInWorker(bytes: Uint8Array, options: SaveInWorkerOptions = {}): Promise<Uint8Array> {
const client = await connect(options);
try {
await using doc = await client.open(bytes, options);
return await doc.save({ mode: "fullRewrite" }, options);
} finally {
client.terminate();
}
}

The promise resolves to the saved file, or rejects with cancelled once the signal aborts. Lamina PDF’s tests run it in Chromium, Firefox and WebKit.

  • connect starts the Web Worker file that ships with @laminapdf/sdk and checks that it comes from the same build as your page.
  • client.open copies the bytes into the Web Worker and returns a remote document, whose methods return promises. await using closes it there when the block ends.
  • The Web Worker saves in steps of 20,000 units of work, about one per object in a full rewrite. Between steps it calls onProgress with done, total and phase, at most every 50 ms, so a small file saves in one step and reports none.
  • Aborting the signal rejects the call at once with cancelled, and error.cause holds the signal’s reason. A save stops at its next step.
  • client.terminate() in finally stops the Web Worker however the save ended, which also stops an open that was still running.
  • A progress bar: in onProgress, set a <progress> element’s value to done and, when the save knows it, its max to total.
  • Large files: pass transfer: true to client.open to move the buffer instead of copying it, which leaves your copy empty. See Keep the page responsive.
  • Several files: call connect once, reuse the client for each file, and terminate it when the page no longer needs it.
  • Edits before the save: apply them with await doc.apply(ops), then save in the default auto mode. It appends them as an incremental save when the file allows one. See Save a PDF.

Next: a Cloudflare Worker that generates a PDF per request.

A Cloudflare Worker

You’ll make a Cloudflare Worker that returns a one-page letter to the name in its URL. You need this to make PDFs on request, such as tickets or receipts, without running a server of your own.

The Cloudflare Worker draws the letter in Helvetica at /?name= and in a bundled Noto Sans at /embedded?name=, then returns the PDF:

packages/sdk/examples/worker/src/index.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;
}
},
};

Open /?name=Ada and your browser shows one A4 page that says “Hello, Ada!” in 24-point type. To configure Wrangler and run it, follow the Cloudflare Workers quick start.

  • init({ text: true }) loads the WebAssembly modules the first time an isolate runs fetch, and returns at once after that. An isolate is one running copy of the Cloudflare Worker, which serves many requests.
  • FONTS maps each path to its font, made once per isolate. Helvetica is one of the standard 14 fonts, so that PDF embeds no font. Noto Sans arrives as bytes from src/fonts/, and that PDF embeds only the glyphs the letter uses.
  • An unknown path gets a 404, and a name longer than MAX_NAME characters gets a 400 before anything is drawn.
  • isNameError turns two codes into a 400 with the error’s JSON. missing-glyph means a character the font lacks, and encoding-full means more than 37 different letters outside Helvetica’s Western European set. Any other error, such as a broken font file, becomes a 500.
  • letter frees its builder in finally, and saveAndFree frees the document once its bytes are copied out, because the isolate goes on to serve other requests.
  • The document: draw your own pages in letter, and keep both finally blocks, so a request that fails still frees what it made.
  • Your fonts: put the font files your documents need in src/fonts/, import each one and add it to FONTS. The quick start’s Wrangler configuration bundles every .ttf and .otf file as bytes.
  • Errors the caller caused: add a code to isNameError when the request can cause it, such as text-overflow for a text box drawn with overflow: "error". See Errors and warnings.
  • A download name: add content-disposition: attachment; filename="letter.pdf" to the headers in pdf, so browsers save the file instead of showing it.

Next: Troubleshooting JavaScript and TypeScript, for the problems people hit most and how to fix them.