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.
Create a PDF
Section titled “Create a PDF”- Hello, world: one page of text in a standard 14 font.
- An invoice: an embedded font, a table of line items, and tags for screen readers.
- Multilingual text: five scripts, each in its own embedded font.
- Images and vectors: paths, colour, transparency, a clip and two images.
- Turn photos into a PDF: one page per photo, fitted on A4, each JPEG embedded as it is.
- Element flow: a report whose parts each start below the one before, over two pages.
- Turn Markdown into a PDF: a report written in Markdown, from the command line, TypeScript or Rust.
- Fill an invoice from JSON: a JSON template filled from data, its line items repeated into a table across pages.
- Links and outlines: links, an outline and page labels.
Edit a PDF
Section titled “Edit a PDF”- 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.
Read a PDF
Section titled “Read a PDF”- Extract text for an LLM: Markdown, JSON with boxes, and chunks for retrieval, in TypeScript and Rust.
Meet a standard
Section titled “Meet a standard”- A PDF/UA report: an accessible report a screen reader can follow.
- A PDF/A archive: a letter for long-term archiving.
- A PDF/A-3 invoice with XML: an invoice with its data attached.
- Make an invoice Factur-X: attach an invoice’s XML to a PDF/A-3 invoice and keep it valid.
Run it in production (TypeScript)
Section titled “Run it in production (TypeScript)”- A 100-page report: the case Lamina PDF times in every runtime.
- Open someone else’s file: a password and tighter limits, with the outcome as a value.
- Save in a Web Worker: progress and cancelling, off the main thread.
- A Cloudflare Worker: a PDF per request.
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:
// 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();}//! The smallest document: one A4 page with a line of text in a standard 14 font.//!//! ```sh//! cargo run -p laminapdf --example hello -- [out-dir] # writes <out-dir>/hello.pdf (default target/examples-out)//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{BuildOptions, Builder, PageSize, PointPt, Pt, SaveOptions, Standard14};
fn main() -> Result<(), Box<dyn Error>> { let out = PathBuf::from(std::env::args().nth(1).unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; std::fs::write(out.join("hello.pdf"), build(BuildOptions::new())?)?; Ok(())}
/// The document's bytes. `options` can fix the file ID, the producer and the creation date, so/// that the same input gives the same bytes on every run.pub(crate) fn build(options: BuildOptions) -> Result<Vec<u8>, Box<dyn Error>> { let mut b = Builder::new(options); let helvetica = b.standard_font(Standard14::Helvetica)?; let mut page = b.page(PageSize::A4); // Page space: points from the top-left corner, y down; `y` is the text's baseline. page.surface().text( "Hello, world!", &helvetica, Pt::new(24.0), PointPt::from_points(72.0, 96.0), )?; page.finish()?; let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
The result is one page with the line near its top-left corner. The Result tab shows it, with a link to the PDF.
How it works
Section titled “How it works”- The builder makes an A4 page, and the page’s surface is what you draw on.
atis 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.
usingin TypeScript frees both as soon as the function ends.
What to change
Section titled “What to change”- 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:
// 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];}//! 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. Run it with `cargo run -p laminapdf --example invoice -- <font.ttf> [out-dir]`.
use laminapdf::{ Alignment, BuildError, BuildOptions, Builder, FontHandle, Metadata, PageSize, PointPt, Pt, RectPt, SaveOptions, Standard14, Surface, TagKind, TextBoxOptions,};
const ITEMS: [(&str, u32, f64); 4] = [ ("Widgets, blue (W-100)", 3, 12.00), ("Gadget with fine-tuned dials", 1, 79.90), ("Café-grade sprockets", 12, 1.25), ("Delivery", 1, 4.50),];const ADDRESS: &str = "Acme Widgets Ltd · 1 Example Street · London";const PAGE: PageSize = PageSize::A4;const MARGIN: f64 = 56.0;const RIGHT_EDGE: f64 = PAGE.width.get() - MARGIN;const TITLE_AT: PointPt = PointPt::from_points(MARGIN, 80.0);const ADDRESS_AT: PointPt = PointPt::from_points(MARGIN, 100.0);const TITLE: Pt = Pt::new(24.0);const BODY: Pt = Pt::new(11.0);const FIRST_ROW: f64 = 160.0;const ROW_HEIGHT: f64 = 24.0;/// The quantity's and the amount's columns, each a width ending this far left of the right edge.const COLUMNS: [(f64, f64); 2] = [(40.0, 169.0), (100.0, 0.0)];/// A cell's box starts this far above its row's baseline and is this tall.const CELL_RISE: f64 = 12.0;const CELL_HEIGHT: f64 = 16.0;
fn main() -> Result<(), Box<dyn std::error::Error>> { let mut args = std::env::args().skip(1); let font = std::fs::read(args.next().ok_or("usage: invoice <font.ttf> [out-dir]")?)?; let out = std::path::PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let pdf = build(BuildOptions::new(), font)?; Ok(std::fs::write(out.join("invoice.pdf"), pdf)?)}
/// The bytes, in `font` (TrueType or OpenType); `options` can fix the file ID, producer and date.pub(crate) fn build(options: BuildOptions, font: Vec<u8>) -> Result<Vec<u8>, Box<dyn std::error::Error>> { let mut b = Builder::new(options.with_tagged(true)); draw(&mut b, font)?; Ok(b.finish()?.save(&SaveOptions::new())?.bytes)}
/// Draws the invoice's one page into `b` and sets its title, author and language.pub(crate) fn draw(b: &mut Builder, font: Vec<u8>) -> Result<(), Box<dyn std::error::Error>> { let (font, bold) = (b.font_bytes(font)?, b.standard_font(Standard14::HelveticaBold)?); let mut page = b.page(PAGE); let s = page.surface(); s.text("Invoice 42", &bold, TITLE, TITLE_AT)?.tag(TagKind::H1); s.text(ADDRESS, &font, BODY, ADDRESS_AT)?.tag(TagKind::P); items(s, &font)?; let total: f64 = ITEMS.iter().map(|(_, qty, price)| f64::from(*qty) * price).sum(); let (total, below_items) = (format!("Total € {total:.2}"), u32::try_from(ITEMS.len())?); let area = cell(COLUMNS[1], row_baseline(below_items)); s.tag(TagKind::P, |s| right_aligned(s, &font, &total, area))?; page.finish()?; let metadata = Metadata::default().with_title("Invoice 42"); b.metadata(metadata.with_author("Acme Widgets Ltd")).lang("en-GB"); Ok(())}
/// The table of line items: what, how many, and the amount, right-aligned.fn items(s: &mut Surface, font: &FontHandle) -> Result<(), BuildError> { s.tag(TagKind::Table, |s| { for (row, (item, qty, price)) in (0_u32..).zip(ITEMS) { let y = row_baseline(row); s.tag(TagKind::TR, |s| { s.text(item, font, BODY, PointPt::from_points(MARGIN, y))? .tag(TagKind::TD); let amount = format!("€ {:.2}", f64::from(qty) * price); for (text, column) in [qty.to_string(), amount].iter().zip(COLUMNS) { s.tag(TagKind::TD, |s| right_aligned(s, font, text, cell(column, y)))?; } Ok(()) })?; } Ok(()) })}
/// The baseline of row `row` of the table.fn row_baseline(row: u32) -> f64 { FIRST_ROW + ROW_HEIGHT * f64::from(row)}
/// The box of a cell in `column` (width, distance from the right edge) on the row at `baseline`.fn cell((width, inset): (f64, f64), baseline: f64) -> RectPt { RectPt::from_points(RIGHT_EDGE - inset - width, baseline - CELL_RISE, width, CELL_HEIGHT)}
/// `text` in `area`, in the body size, aligned to its right edge.fn right_aligned(s: &mut Surface, font: &FontHandle, text: &str, area: RectPt) -> Result<(), BuildError> { let right = TextBoxOptions::new().with_align(Alignment::End); s.text_box(text, font, BODY, area, &right).map(|_| ())}
The result is one A4 page with its body set in Noto Sans. The Result tab shows it, with a link to the PDF.
How it works
Section titled “How it works”- 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.cellworks 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. Thetagoption ands.tag(…)make the heading anH1, the address and the total each a paragraph (P), and the items aTableof rows (TR) and cells (TD).metadatasets the title and author, andlang("en-GB")tells a screen reader which language to speak.
What to change
Section titled “What to change”- The line items: edit
ITEMS. Each row sitsROW_HEIGHTpoints below the one before, and the total follows the last row. - The columns: each pair in
COLUMNSis 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 withmissing-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:
// 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();}//! 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. Run it with `cargo run -p//! laminapdf --example invoice_from_json -- invoice.json invoice-data.json regular.ttf bold.ttc`.
use std::error::Error;
use laminapdf::flow::document::{Resources, fill};use laminapdf::{BuildOptions, Builder, Font, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let paths: Vec<String> = std::env::args().skip(1).collect(); let [template, data, regular, bold] = paths.as_slice() else { return Err("arguments: <invoice.json> <invoice-data.json> <regular.ttf> <bold.ttc>".into()); }; let read = |path: &String| std::fs::read(path); let pdf = build( BuildOptions::new(), &read(template)?, &read(data)?, read(regular)?, read(bold)?, )?; std::fs::create_dir_all("target/examples-out")?; Ok(std::fs::write("target/examples-out/invoice_from_json.pdf", pdf)?)}
/// The invoice's bytes. `options` can fix the file ID, the producer and the creation date.pub(crate) fn build( options: BuildOptions, template: &[u8], data: &[u8], regular: Vec<u8>, bold: Vec<u8>,) -> Result<Vec<u8>, Box<dyn Error>> { let document = fill(&serde_json::from_slice(template)?, &serde_json::from_slice(data)?)?; let options = document .profiles() .into_iter() .fold(options, BuildOptions::with_profile); let mut b = Builder::new(options); let resources = Resources::new() .with_font("regular", &b.font(Font::from_bytes(regular)?)?) .with_font("bold", &b.font(Font::from_collection(bold, 1)?)?); b.document(&document, &resources)?; Ok(b.finish()?.save(&SaveOptions::new())?.bytes)}


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.
How it works
Section titled “How it works”fill(in TypeScript,builder.flowgivendata) 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/numberis thenumberinsideinvoice, and/items/0the 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’tfalseornull. 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
bodyandstrong, and each style names a font. The fonts’ bytes come beside the template, throughResourcesin Rust andfontsin 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.
What to change
Section titled “What to change”- 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. Itsdata.pointernames the value, such as/blocks/2/spaceAftr, and itsdidYouMeanthe closest key the format knows. In TypeScript,tscrefuses a misspelt key in a template you write in your code as aFlowTemplate; a template read from a file is checked whenflowreads it. - A value the data lacks: filling fails with
template-data-missingand 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. Thelaminapdfcrate and@laminapdf/sdkboth ship it asdocs/schemas/document.schema.json.
Build it without code
Section titled “Build it without code”The command-line tool fills the template and lays it out in one command, giving each font by the name the template uses:
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:
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-1The 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:
// 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();}//! 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 is checked against PDF/UA-1, so every font is embedded. Run it with `cargo run -p//! laminapdf --example markdown_to_pdf -- report.md regular.ttf bold.ttc arabic.ttf//! devanagari.ttf photo.jpg`.
use std::error::Error;
use laminapdf::flow::{PageRegion, PageTemplate, TextStyle};use laminapdf::markdown::{MarkdownBuildOptions, MarkdownFonts};use laminapdf::{BuildOptions, Builder, Font, Image, PageSize, Profile, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let paths: Vec<String> = std::env::args().skip(1).collect(); let [markdown, regular, bold, arabic, hindi, photo] = paths.as_slice() else { return Err("arguments: <report.md> <regular.ttf> <bold.ttc> <arabic.ttf> <devanagari.ttf> <photo.jpg>".into()); }; let read = |path: &String| std::fs::read(path); let fonts = [read(regular)?, read(bold)?, read(arabic)?, read(hindi)?]; let markdown = std::fs::read_to_string(markdown)?; let pdf = build(BuildOptions::new(), &markdown, fonts, read(photo)?)?; std::fs::create_dir_all("target/examples-out")?; Ok(std::fs::write("target/examples-out/markdown_to_pdf.pdf", pdf)?)}
/// The report's bytes. `options` can fix the file ID, the producer and the creation date.pub(crate) fn build( options: BuildOptions, markdown: &str, fonts: [Vec<u8>; 4], photo: Vec<u8>,) -> Result<Vec<u8>, Box<dyn Error>> { let [regular, bold, arabic, hindi] = fonts; let mut b = Builder::new(options.with_profile(Profile::PdfUa1)); let regular = b.font(Font::from_bytes(regular)?)?; let fonts = MarkdownFonts::new(®ular) .with_bold(&b.font(Font::from_collection(bold, 1)?)?) .with_fallback(&b.font(Font::from_bytes(arabic)?)?) .with_fallback(&b.font(Font::from_bytes(hindi)?)?); // A5 pages, so the table runs across two of them, with the page number in the footer. let footer = PageRegion::new().with_center("Page {page} of {pages}"); let pages = PageTemplate::new(PageSize::A5).with_furniture(None, Some(footer), &TextStyle::new(®ular, 8.0)); let options = MarkdownBuildOptions::new() .with_fonts(fonts) .with_template(pages) .with_contents(2) .with_image("photo.jpg", Image::jpeg(photo)?); let report = b.markdown(markdown, &options)?; if let Some(warning) = report.warnings.first() { return Err(format!("the Markdown has something the PDF leaves out: {}", warning.code()).into()); } Ok(b.finish()?.save(&SaveOptions::new())?.bytes)}




The result is four A5 pages that meet PDF/UA-1. The Result tab shows them, with a link to the PDF.
How it works
Section titled “How it works”- 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: valuelines 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 withmarkdown-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.
What to change
Section titled “What to change”- 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 letteron the command line,page: { size: "Letter" }in TypeScript, or aPageTemplatein Rust. The template also sets the margins, a header and the footer. - No contents page: remove
contents(with_contentsin Rust). The command line never adds one. - An AI agent:
laminapdf mcp --root DIR --allow-writeserves thelaminapdf_buildtool to agents that speak MCP. It takes the Markdown inline or as a file, reads fonts and images only insideDIR, 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:
// 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();}//! 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).//!//! ```sh//! cargo run -p laminapdf --example multilingual -- latin.ttf arabic.ttf devanagari.ttf hebrew.ttf chinese.otf//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ Alignment, BuildOptions, Builder, Direction, PageSize, PointPt, Pt, RectPt, SaveOptions, TextBoxOptions,};
/// Each script's line, its paragraph and the paragraph's direction, in the order of the fonts.const SCRIPTS: [(&str, &str, Direction); 5] = [ ( "Latin: the office staff fill the affine waffle flask", "A paragraph breaks at spaces and fits the width of its box, line by line.", Direction::LeftToRight, ), ( "مرحبا بالعالم السلام عليكم", "مرحبا بالعالم السلام عليكم مرحبا بالعالم السلام عليكم", Direction::RightToLeft, ), ( "नमस्ते दुनिया। हिन्दी पाठ का परीक्षण", "नमस्ते दुनिया। हिन्दी पाठ का परीक्षण नमस्ते दुनिया।", Direction::LeftToRight, ), ( "שלום עולם וברוכים הבאים", "שלום עולם וברוכים הבאים שלום עולם וברוכים הבאים", Direction::RightToLeft, ), ( "你好世界,这是中文字体子集测试。", "你好世界,这是中文字体子集测试。你好世界,这是中文。", Direction::LeftToRight, ),];const MARGIN: f64 = 56.0;const FIRST_BASELINE: f64 = 80.0;/// The distance from one script's line to the next one's.const SCRIPT_HEIGHT: f64 = 140.0;/// The paragraph's box: this far below the line, this wide and this tall.const PARAGRAPH_DROP: f64 = 14.0;const PARAGRAPH_WIDTH: f64 = 220.0;const PARAGRAPH_HEIGHT: f64 = 100.0;
fn main() -> Result<(), Box<dyn Error>> { let mut args: Vec<String> = std::env::args().skip(1).collect(); let out = PathBuf::from(if args.len() > SCRIPTS.len() { args.remove(SCRIPTS.len()) } else { "target/examples-out".into() }); let fonts = args.iter().map(std::fs::read).collect::<Result<Vec<_>, _>>()?; std::fs::create_dir_all(&out)?; std::fs::write(out.join("multilingual.pdf"), build(BuildOptions::new(), fonts)?)?; Ok(())}
/// The document's bytes, with one font per script in `fonts` (in the order of [`SCRIPTS`])./// `options` can fix the file ID, the producer and the creation date.pub(crate) fn build(options: BuildOptions, fonts: Vec<Vec<u8>>) -> Result<Vec<u8>, Box<dyn Error>> { if fonts.len() != SCRIPTS.len() { return Err(format!("{} fonts, one per script, are needed", SCRIPTS.len()).into()); } let mut b = Builder::new(options); let fonts = fonts .into_iter() .map(|bytes| b.font_bytes(bytes)) .collect::<Result<Vec<_>, _>>()?; let mut page = b.page(PageSize::A4); let s = page.surface(); for (row, ((line, paragraph, direction), font)) in (0_u32..).zip(SCRIPTS.iter().zip(&fonts)) { let y = FIRST_BASELINE + SCRIPT_HEIGHT * f64::from(row); s.text(line, font, Pt::new(16.0), PointPt::from_points(MARGIN, y))?; // A narrow box breaks the paragraph into lines; right-to-left paragraphs start at the right. let options = TextBoxOptions::new() .with_direction(*direction) .with_align(Alignment::Start); let area = RectPt::from_points(MARGIN, y + PARAGRAPH_DROP, PARAGRAPH_WIDTH, PARAGRAPH_HEIGHT); s.text_box(paragraph, font, Pt::new(12.0), area, &options)?; } page.finish()?; let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
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.
How it works
Section titled “How it works”Font.fromBytes(font_bytesin 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.
textBoxbreaks 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, soalign: "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.
What to change
Section titled “What to change”- Your own scripts: change
SCRIPTSand pass one font per row, in the same order. A character the font lacks fails withmissing-glyph. - The paragraph’s box:
PARAGRAPH_WIDTHandPARAGRAPH_HEIGHTset its size. Lines that don’t fit are left out, unless you passoverflow: "error"(Overflow::Error) to fail withtext-overflowinstead. - Alignment and spacing:
alignalso takes"end","left","right"or"center", andlineHeight(with_line_height) sets the distance between baselines, 1.2 times the size by default. - Ligatures and other OpenType features:
features: ["liga=0"]ontextortextBoxturns the ligatures off. In Rust, callfeatureson the run orwith_featureon 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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --example images_and_vectors -- photo.jpg [out-dir] # writes images_and_vectors.pdf//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ BlendMode, BuildOptions, Builder, Color, Dash, FillRule, Image, LineCap, Matrix, PageSize, PathBuilder, PointPt, Pt, RectPt, SaveOptions, StrokeStyle, Surface,};
/// The RGBA gradient's side, in pixels.const GLOW_SIDE: u8 = 16;
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let photo = std::fs::read(args.next().ok_or("usage: images_and_vectors <photo.jpg> [out-dir]")?)?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; std::fs::write(out.join("images_and_vectors.pdf"), build(BuildOptions::new(), photo)?)?; Ok(())}
/// The document's bytes, with `photo` (a JPEG) on the page. `options` can fix the file ID, the/// producer and the creation date.pub(crate) fn build(options: BuildOptions, photo: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut b = Builder::new(options); let photo = Image::jpeg(photo)?; let glow = Image::rgba(u32::from(GLOW_SIDE), u32::from(GLOW_SIDE), &gradient())?; let mut page = b.page(PageSize::A4); let s = page.surface(); shapes(s)?; overlapping_discs(s); images(s, &photo, &glow); page.finish()?; let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
/// A square gradient whose alpha falls off towards the right.fn gradient() -> Vec<u8> { (0..GLOW_SIDE) .flat_map(|y| (0..GLOW_SIDE).flat_map(move |x| [x * 16, y * 16, 200, 255 - x * 15])) .collect()}
/// A rectangle, a circle and a dashed, round-capped Bézier curve.fn shapes(s: &mut Surface) -> Result<(), Box<dyn Error>> { let at = PointPt::from_points; s.fill_color(Color::rgb(0.9, 0.3, 0.2)) .path(|p| _ = p.rect(RectPt::from_points(56.0, 56.0, 160.0, 100.0))) .fill(FillRule::NonZero); s.fill_color(Color::cmyk(0.8, 0.1, 0.0, 0.0)) .path(|p| _ = p.circle(at(330.0, 106.0), Pt::new(50.0))) .fill(FillRule::NonZero); let dashed = StrokeStyle { width: Pt::new(3.0), cap: LineCap::Round, dash: Some(Dash::new(vec![12.0, 8.0], 0.0)), ..StrokeStyle::default() }; s.stroke_color(Color::hex("#2a9d8f")?) .path(|p| { p.move_to(at(56.0, 220.0)) .cubic_to(at(180.0, 140.0), at(300.0, 300.0), at(539.0, 200.0)); }) .stroke(&dashed); Ok(())}
/// Two translucent discs, the second multiplied onto the first.fn overlapping_discs(s: &mut Surface) { let disc = |x: f64| move |p: &mut PathBuilder| _ = p.circle(PointPt::from_points(x, 330.0), Pt::new(60.0)); s.save().opacity(0.6, 1.0).fill_color(Color::gray(0.3)); s.path(disc(120.0)).fill(FillRule::NonZero); s.blend_mode(BlendMode::Multiply).fill_color(Color::rgb(1.0, 0.8, 0.0)); s.path(disc(190.0)).fill(FillRule::NonZero).restore();}
/// The photo clipped to an ellipse, and the gradient rotated by 30 degrees.fn images(s: &mut Surface, photo: &Image, glow: &Image) { s.save() .path(|p| _ = p.ellipse(RectPt::from_points(300.0, 270.0, 239.0, 120.0))) .clip(FillRule::NonZero); s.image(photo, RectPt::from_points(300.0, 250.0, 239.0, 160.0)) .restore(); let placement = Matrix::translate(150.0, 520.0).after(&Matrix::rotate(30.0)); s.save().transform(placement); s.image(glow, RectPt::from_points(-60.0, -60.0, 120.0, 120.0)).restore();}
The result is one A4 page with every shape and both images. The Result tab shows it, with a link to the PDF.
How it works
Section titled “How it works”path(p => …)builds a shape and returns it unpainted.fillandstrokepaint it, andcliplimits 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 hasColor::gray,rgb,cmykandhex. save()andrestore()bracket each group of drawings, so the opacity, blend mode, clip and rotation set inside stop atrestore().- Both discs are 60% opaque, and
multiplydarkens the area where the second disc covers the first. Image.jpegembeds the photo as it is, without decoding it.Image.rgbatakes 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.
What to change
Section titled “What to change”- A PNG instead of the JPEG:
Image.png(bytes)(Image::pngin 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_strokein Rust) paints both at once. - Another blend mode:
"screen"lightens where"multiply"darkens.BlendModelists all sixteen. - Alternate text: pass a description as the third argument of
image(figurein 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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --example images_to_pdf -- out-dir photo.jpg [more.jpg …] # writes out-dir/images_to_pdf.pdf//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{BuildOptions, Image, ImagePages, ImagesOptions, PageSize, Pt, SaveOptions, images_to_pdf};
/// The space around each photo, in millimetres.const MARGIN_MM: f64 = 15.0;const USAGE: &str = "usage: images_to_pdf <out-dir> <photo.jpg> [more.jpg …]";
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let out = PathBuf::from(args.next().ok_or(USAGE)?); let photos = args.map(std::fs::read).collect::<Result<Vec<_>, _>>()?; if photos.is_empty() { return Err(USAGE.into()); } std::fs::create_dir_all(&out)?; std::fs::write(out.join("images_to_pdf.pdf"), build(BuildOptions::new(), photos)?)?; Ok(())}
/// The document's bytes, one page per photo (JPEGs). `options` can fix the file ID, the producer/// and the creation date.pub(crate) fn build(options: BuildOptions, photos: Vec<Vec<u8>>) -> Result<Vec<u8>, Box<dyn Error>> { let images = photos.into_iter().map(Image::jpeg).collect::<Result<Vec<_>, _>>()?; let options = ImagesOptions::new() .with_pages(ImagePages::Fit(PageSize::A4)) .with_margin(Pt::from_mm(MARGIN_MM)) .with_build(options); let mut doc = images_to_pdf(&images, &options)?; Ok(doc.save(&SaveOptions::new())?.bytes)}


The result has two pages: a colour photo and a greyscale one. The Result tab shows them, with a link to the PDF.
How it works
Section titled “How it works”- 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.
What to change
Section titled “What to change”- 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::ImageSizein Rust). Each page is then its photo’s size at the resolution its file records, or atdefaultDpi(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 ofImage.jpeg(bytes)(Image::pngin 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:
// 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)];}//! 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. Run it with `cargo run -p laminapdf --example element_flow -- photo.jpg`.
use std::error::Error;
use laminapdf::{ BuildOptions, Builder, Color, FontHandle, Image, Overflow, PageSize, Pt, RectPt, SaveOptions, Standard14::{Helvetica, HelveticaBold}, StrokeStyle, Surface, TextBoxOptions, TextLayout,};
const PAGE: PageSize = PageSize::A5;const MARGIN: f64 = 48.0;const WIDTH: f64 = PAGE.width.get() - 2.0 * MARGIN;const BOTTOM: f64 = PAGE.height.get() - MARGIN;const TITLE: Pt = Pt::new(18.0);const BODY: Pt = Pt::new(11.0);const GAP: f64 = 10.0;const PHOTO_HEIGHT: f64 = WIDTH / 1.5; // a 3:2 photo across the text column
/// What the report says. Empty `notes` take no space; blank lines separate the body's paragraphs.pub(crate) struct Report<'a> { pub(crate) title: &'a str, pub(crate) summary: &'a str, pub(crate) notes: &'a str, pub(crate) body: &'a str,}
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let photo = std::fs::read(args.next().ok_or("usage: element_flow <photo.jpg> [out-dir]")?)?; let out = std::path::PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); let report = Report { title: "Third-quarter report", summary: "Revenue rose twelve per cent over the quarter, led by the new reader and its offline mode.", notes: "Figures are unaudited.", body: "Pages now appear as soon as they are read, and support requests about slow files fell by a third.", }; let pdf = build(BuildOptions::new(), photo, &report)?; std::fs::create_dir_all(&out)?; Ok(std::fs::write(out.join("element_flow.pdf"), pdf)?)}
/// The report's bytes, with `photo` (a JPEG) below its notes. `options` can fix the file ID, the/// producer and the creation date.pub(crate) fn build(options: BuildOptions, photo: Vec<u8>, report: &Report) -> Result<Vec<u8>, Box<dyn Error>> { let mut b = Builder::new(options); let fonts = [b.standard_font(HelveticaBold)?, b.standard_font(Helvetica)?]; let photo = Image::jpeg(photo)?; let mut page = b.page(PAGE); let mut y = header(page.surface(), &fonts, &photo, report)?; let (mut rest, mut new_page) = (report.body.trim_end(), false); loop { let s = page.surface(); let layout = s.text_box(rest, &fonts[1], BODY, area(y), &TextBoxOptions::new())?; // A clipped box still drew its first lines: the rest goes on a new page, from its top. let Some(cut) = layout.overflow else { break }; if cut == 0 && new_page { return Err("a line of the body is taller than the page".into()); } (rest, y, new_page) = (rest[cut..].trim_start(), MARGIN, true); page.finish()?; page = b.page(PAGE); } page.finish()?; Ok(b.finish()?.save(&SaveOptions::new())?.bytes)}
/// 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 fails `text-overflow`.fn header(s: &mut Surface, fonts: &[FontHandle; 2], photo: &Image, report: &Report) -> Result<f64, Box<dyn Error>> { let [bold, regular] = fonts; let must_fit = TextBoxOptions::new().with_overflow(Overflow::Error); let mut y = below(&s.text_box(report.title, bold, TITLE, area(MARGIN), &must_fit)?, MARGIN); // A decoration half a gap above the summary. It's stroked: a fill colour would colour the text too. let (rule, gray) = (RectPt::from_points(MARGIN, y - GAP / 2.0, WIDTH, 0.0), Color::gray(0.6)); let line = StrokeStyle::default(); s.stroke_color(gray).path(|p| _ = p.rect(rule)).stroke(&line); for text in [report.summary, report.notes] { y = below(&s.text_box(text, regular, BODY, area(y), &must_fit)?, y); } if y + PHOTO_HEIGHT > BOTTOM { return Err("the photo doesn't fit below the notes".into()); } s.image(photo, RectPt::from_points(MARGIN, y, WIDTH, PHOTO_HEIGHT)); Ok(y + PHOTO_HEIGHT + GAP)}
/// Where the next element starts: a gap below `layout`'s last drawn line, or `y` if it drew none.fn below(layout: &TextLayout, y: f64) -> f64 { layout.bottom().map_or(y, |bottom| bottom.get() + GAP)}
/// The rest of the page's text column, from `y` down to the bottom margin.fn area(y: f64) -> RectPt { RectPt::from_points(MARGIN, y, WIDTH, (BOTTOM - y).max(0.0))}


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.
How it works
Section titled “How it works”Every text box tells you where its text ended, so you never type a position for anything after the first element.
bottomis where the next element can start.textBoxreturns it with the lines it drew: the bottom of the last line that draws something. Rust hasTextLayout::bottom(), andTextRun::bottom()for a single run of text.- Empty text has no
bottom. The notes here are optional. When they’re empty,bottomisundefined(Nonein Rust),belowkeepsywhere 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
yitself. - The rule under the title is a decoration. It’s drawn half a gap above the summary and leaves
yalone. It’s stroked rather than filled: a fill colour stays set and would colour the text drawn after it.
Text that doesn’t fit
Section titled “Text that doesn’t fit”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.
What bottom measures
Section titled “What bottom measures”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.
What stays your job
Section titled “What stays your job”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.
What to change
Section titled “What to change”- Paragraphs a gap apart: draw each paragraph in its own text box and start the next one at
bottomplus the gap, as the summary and notes do. - A line height for the body: pass
lineHeight(with_line_heightin Rust);bottomfollows it. - Two columns: keep a
yfor 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.
Links and outlines
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:
// Links and outlines: four A5 pages joined by links, bookmarks and page labels. The title page// links to a website, to a page and through a named destination; every other page has a linked// text run back to it. The outline is nested and shown when the file opens.import { Builder, type BuilderOptions, Font, type LinkTarget, type Surface } from "@laminapdf/sdk";
const TITLES = ["Title page", "Contents", "Chapter 1", "Chapter 2"] as const;const MARGIN = 36;const TITLE_BASELINE = 60;const TITLE_SIZE = 18;const LINK_SIZE = 12;/** The baselines of the title page's three links. */const LINK_BASELINES = [100, 125, 150] as const;/** A link's clickable box: this wide, this tall, starting this far above the baseline. */const LINK_WIDTH = 220;const LINK_HEIGHT = 20;const LINK_RISE = 15;
/** * The document's bytes. Needs `init({ text: true })`. * * @param options - can fix the file ID, the producer and the creation date. */export function linksAndOutlines(options: BuilderOptions = {}): Uint8Array<ArrayBuffer> { using b = new Builder(options); const font = Font.standard("Helvetica"); b.font(font); b.destination("chapter-2", 3); TITLES.forEach((title, index) => { const page = b.page("A5"); const s = page.surface(); s.text(title, { font, size: TITLE_SIZE, at: [MARGIN, TITLE_BASELINE] }); if (index === 0) titlePageLinks(s, font); else { const link = { target: { type: "page", index: 0 }, contents: "Title page" } as const; s.text("Back to the title page", { font, size: LINK_SIZE, at: [MARGIN, 100], fill: [0, 0.2, 0.8], link }); } page.finish(); }); navigation(b); using doc = b.finish(); return doc.save();}
/** The title page's links: to a website, to a page, and to a named destination. */function titlePageLinks(s: Surface, font: Font): void { const links: readonly (readonly [label: string, target: LinkTarget, contents?: string])[] = [ ["Visit example.com", { type: "uri", uri: "https://example.com/" }, "Example"], ["Go to chapter 1", { type: "page", index: 2 }], ["Go to chapter 2 (named)", { type: "named", name: "chapter-2" }], ]; links.forEach(([label, target, contents], i) => { const baseline = LINK_BASELINES[i] ?? 0; s.text(label, { font, size: LINK_SIZE, at: [MARGIN, baseline] }); s.link([MARGIN, baseline - LINK_RISE, LINK_WIDTH, LINK_HEIGHT], target, contents); });}
/** The outline (bookmarks), the page labels, and the viewer opening with the outline shown. */function navigation(b: Builder): void { b.outline([ { title: "Title page", target: { type: "page", index: 0 } }, { title: "Contents", target: { type: "page", index: 1 }, color: [0, 0, 0.6] }, { title: "Chapters", open: true, bold: true, children: [ { title: "Chapter 1", target: { type: "page", index: 2 } }, { title: "Chapter 2", target: { type: "named", name: "chapter-2" }, italic: true }, ], }, ]); b.pageLabels([ { start: 0, style: "lowerRoman" }, { start: 2, style: "decimal" }, ]).viewerPreferences({ pageMode: "outlines" });}//! Links and outlines: four A5 pages joined by links, bookmarks and page labels.//!//! The title page has a URI link, a link to a page and one through a named destination; every//! other page has a linked text run back to it. The outline (bookmarks) is nested and open in//! the viewer, and the pages are labelled i, ii, 1, 2.//!//! ```sh//! cargo run -p laminapdf --example links_and_outlines -- [out-dir] # writes <out-dir>/links_and_outlines.pdf//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ BuildOptions, Builder, Color, Fit, FontHandle, LabelStyle, LinkTarget, OutlineEntry, PageLabel, PageMode, PageSize, PointPt, Pt, RectPt, SaveOptions, Standard14, Surface, ViewerPreferences,};
const TITLES: [&str; 4] = ["Title page", "Contents", "Chapter 1", "Chapter 2"];const MARGIN: f64 = 36.0;const TITLE_AT: PointPt = PointPt::from_points(MARGIN, 60.0);const BACK_AT: PointPt = PointPt::from_points(MARGIN, 100.0);const TITLE_SIZE: Pt = Pt::new(18.0);const LINK_SIZE: Pt = Pt::new(12.0);/// The baselines of the title page's three links.const LINK_BASELINES: [f64; 3] = [100.0, 125.0, 150.0];/// A link's clickable box: this wide, this tall, starting this far above the baseline.const LINK_WIDTH: f64 = 220.0;const LINK_HEIGHT: f64 = 20.0;const LINK_RISE: f64 = 15.0;
fn main() -> Result<(), Box<dyn Error>> { let out = PathBuf::from(std::env::args().nth(1).unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; std::fs::write(out.join("links_and_outlines.pdf"), build(BuildOptions::new())?)?; Ok(())}
/// The document's bytes. `options` can fix the file ID, the producer and the creation date.pub(crate) fn build(options: BuildOptions) -> Result<Vec<u8>, Box<dyn Error>> { let mut b = Builder::new(options); let helvetica = b.standard_font(Standard14::Helvetica)?; b.destination("chapter-2", 3, Fit::Page); for (index, title) in (0_u32..).zip(TITLES) { let mut page = b.page(PageSize::A5); let s = page.surface(); s.text(title, &helvetica, TITLE_SIZE, TITLE_AT)?; if index == 0 { title_page_links(s, &helvetica)?; } else { s.text("Back to the title page", &helvetica, LINK_SIZE, BACK_AT)? .fill(Color::rgb(0.0, 0.2, 0.8)) .link(LinkTarget::page(0), Some("Title page".into())); } page.finish()?; } navigation(&mut b)?; let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
/// The title page's links: to a website, to a page, and to a named destination.fn title_page_links(s: &mut Surface, font: &FontHandle) -> Result<(), Box<dyn Error>> { let site = LinkTarget::Uri("https://example.com/".into()); let links = [ ("Visit example.com", site, Some("Example")), ("Go to chapter 1", LinkTarget::page(2), None), ("Go to chapter 2 (named)", LinkTarget::Named("chapter-2".into()), None), ]; for ((label, target, contents), baseline) in links.into_iter().zip(LINK_BASELINES) { s.text(label, font, LINK_SIZE, PointPt::from_points(MARGIN, baseline))?; let area = RectPt::from_points(MARGIN, baseline - LINK_RISE, LINK_WIDTH, LINK_HEIGHT); s.link(area, target, contents.map(String::from)); } Ok(())}
/// The outline (bookmarks), the page labels, and the viewer opening with the outline shown.fn navigation(b: &mut Builder) -> Result<(), Box<dyn Error>> { b.outline(vec![ OutlineEntry::new("Title page", LinkTarget::page(0)), OutlineEntry::new("Contents", LinkTarget::page(1)).with_color(0.0, 0.0, 0.6), OutlineEntry::heading("Chapters") .open(true) .bold() .with_child(OutlineEntry::new("Chapter 1", LinkTarget::page(2))) .with_child(OutlineEntry::new("Chapter 2", LinkTarget::Named("chapter-2".into())).italic()), ])?; b.page_labels(vec![ PageLabel::new(0, Some(LabelStyle::LowerRoman)), PageLabel::new(2, Some(LabelStyle::Decimal)), ]) .viewer_preferences(ViewerPreferences::default().with_page_mode(PageMode::Outlines)); Ok(())}




The result is four A5 pages with an outline and page labels. The Result tab shows it, with a link to the PDF.
How it works
Section titled “How it works”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 withpage-index-out-of-rangeand a missing name withunknown-destination.- On the other pages, the
linkoption oftext(.link(…)on the run in Rust) makes the blue run itself the link, with no box to work out. contentsdescribes a link in words, for viewers and screen readers. Accessible PDFs need one on every link.outlinebuilds the bookmarks. “Chapters” has no target, so it’s a heading, shown open and in bold with both chapters inside it.pageLabelsnumbers 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.
What to change
Section titled “What to change”- Where a page link lands: add a
fitto the target, such asfit: { type: "width" }(Fit::Widthin Rust) to fill the window with the page’s width.destinationtakes one too. - The page numbers: a label also takes a
prefixand afirstnumber, so{ start: 2, style: "decimal", prefix: "A-" }numbers the chapters A-1 and A-2. - The panel on open:
pageModealso takes"thumbnails","attachments"or"none". - A title and an author: add
metadata({ title, author }), anddisplayDocTitle: truein 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:
// 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" });}//! Generate a document, then open its bytes, edit them and save incrementally.//!//! The edit changes the metadata with an op (undoable and serialisable), and the//! incremental save keeps the generated bytes as they are, with one revision appended.//!//! ```sh//! cargo run -p laminapdf --example generate_then_edit -- [out-dir] # writes <out-dir>/generate_then_edit.pdf//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ BuildOptions, Builder, Document, Metadata, MetadataPatch, Op, OpenOptions, PageSize, PdfDate, PointPt, Pt, SaveMode, SaveOptions, SetMetadata, Standard14,};
fn main() -> Result<(), Box<dyn Error>> { let out = PathBuf::from(std::env::args().nth(1).unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let bytes = build(BuildOptions::new(), None)?; std::fs::write(out.join("generate_then_edit.pdf"), bytes)?; Ok(())}
/// The generated file followed by the edit's revision. `edited_at` is recorded as the/// modification date; `options` can fix the file ID, the producer and the creation date.pub(crate) fn build(options: BuildOptions, edited_at: Option<PdfDate>) -> Result<Vec<u8>, Box<dyn Error>> { let generated = generate(options)?; edit(generated, edited_at)}
/// A one-page draft, saved (a new document is always saved as a full rewrite).pub(crate) fn generate(options: BuildOptions) -> Result<Vec<u8>, Box<dyn Error>> { let mut b = Builder::new(options); let helvetica = b.standard_font(Standard14::Helvetica)?; let mut page = b.page(PageSize::A4); page.surface().text( "Draft report", &helvetica, Pt::new(20.0), PointPt::from_points(72.0, 96.0), )?; page.finish()?; b.metadata(Metadata::default().with_title("Draft report")); Ok(b.finish()?.save(&SaveOptions::new())?.bytes)}
/// Opens `bytes`, edits the metadata (the Info dictionary and the XMP packet together) in one/// transaction (which `undo` could revert) and saves incrementally: `bytes` unchanged, then the/// appended revision.fn edit(bytes: Vec<u8>, edited_at: Option<PdfDate>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let patch = MetadataPatch::new() .title(Some("Final report")) .authors(&["Ada Lovelace"]); doc.apply(vec![Op::from(SetMetadata::new(patch, edited_at))])?; let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}
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.
How it works
Section titled “How it works”- A new document has no original bytes to append to, so the draft’s save is a full rewrite.
Document.open(Document::open_bytesin Rust) reads the draft. Your edits sit beside its bytes and never change them; see How Lamina PDF thinks about a PDF.setMetadatachanges the title, authors and other facts a viewer shows in a file’s properties.transactapplies it as one transaction, whichundoreverts as a whole. In Rust,applytakes 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.editedAtis the modification date to record, a PDF date such asD: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.
setMetadatachanges both, so they agree.
What to change
Section titled “What to change”- More edits in the same revision: add them inside the callback, such as
tx.rotatePage(doc.page(0).id, 90)(RotatePagein Rust). See Edit a PDF. - Removing an entry: pass
nullfor 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 leavemodeout 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_login 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:
// 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);}//! 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.//!//! ```sh//! cargo run -p laminapdf --example edit_metadata -- in.pdf <save-time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ Document, MetadataKey, MetadataPatch, Op, OpenOptions, PdfDate, RemoveMetadata, SaveMode, SaveOptions, SetMetadata,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: edit_metadata in.pdf <save-time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); // The time of the save, which your app takes from its clock. let saved_at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let edited = edit(std::fs::read(input)?, saved_at)?; std::fs::write(out.join("edit_metadata.pdf"), edited)?; Ok(())}
/// The document with its metadata edited, saved incrementally at `saved_at`.pub(crate) fn edit(bytes: Vec<u8>, saved_at: PdfDate) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?;
let patch = MetadataPatch::new() .title(Some("Quarterly figures")) .authors(&["Ada Lovelace", "Charles Babbage"]); doc.apply(vec![ Op::from(SetMetadata::new(patch, Some(saved_at))), Op::from(RemoveMetadata::new(vec![MetadataKey::Keywords])), ])?;
let options = SaveOptions::new() .with_mode(SaveMode::Incremental) .with_metadata_date(saved_at); let plan = doc.plan(&options)?; if let Some(refusal) = plan.refusal { return Err(format!("the save would be refused: {}", refusal.as_str()).into()); } for warning in &plan.conformance_warnings { eprintln!("warning: {}", warning.code()); } Ok(doc.save(&options)?.bytes)}
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.
How it works
Section titled “How it works”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 indisagreements.setMetadata(SetMetadatain Rust) takes a patch: a value sets a field,nullremoves 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;.atis the modification date the edit records, a PDF date such asD:20261110093000Zthat 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,refusaliswould-invalidate-signatures, because a certification allows no metadata change.conformanceWarningslists 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 neithermetadataDatenorinstanceIdstamps nothing.
What to change
Section titled “What to change”- 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. PassreplaceMalformed: trueto 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’sstillInEarlierRevisionssays 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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example set_initial_view -- in.pdf <page-number> [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ Document, Op, OpenAt, OpenOptions, OpenTarget, OpenZoom, PageMode, SaveOptions, SetInitialView, WindowPreferencesPatch,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: set_initial_view in.pdf <page-number> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); let number: u32 = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let index = number.checked_sub(1).ok_or("page numbers start at 1")?; let edited = open_on(std::fs::read(input)?, index)?; std::fs::write(out.join("set_initial_view.pdf"), edited)?; Ok(())}
/// `bytes` 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.pub(crate) fn open_on(bytes: Vec<u8>, index: u32) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let page = doc.page_info(index)?.id;
let mut view = SetInitialView::default() .with_page_mode(Some(PageMode::Outlines)) .with_preferences(WindowPreferencesPatch::default().with_display_doc_title(true)); // An open action that runs a script or another action is never replaced, so leave the page out. if let OpenTarget::Action(kind) = doc.initial_view()?.open { eprintln!("the file runs a {kind} action when it opens; keeping it"); } else { view = view.with_open(Some(OpenAt::new(page, OpenZoom::FitWidth))); } doc.apply(vec![Op::from(view)])?; Ok(doc.save(&SaveOptions::new())?.bytes)}



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.
How it works
Section titled “How it works”initialView()reads how the file asks to open. Itsopenis"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(SetInitialViewin Rust) takes a patch: a value sets a field,nullremoves it, and a field you leave out stays as the file has it.opennames the page by its ID and azoom:"fitWidth","fitPage","default"(the reader’s own zoom) or a percentage from 1 to 6400.pageModeis the panel beside the page:"outlines"for bookmarks,"thumbnails","attachments","optionalContent"for layers,"fullScreen"or"none".preferencesholds the window’s requests, such asdisplayDocTitlefor the title in the title bar.truesets one;falseremoves 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.
What to change
Section titled “What to change”- Another page layout: add
pageLayout, such as"twoPageRight"for two pages side by side with the cover alone. - The reader’s defaults again: pass
nullfor each field you set,openincluded. - 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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example edit_bookmarks -- in.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ AddOutlineItem, Document, MoveOutlineItem, Op, OpenOptions, OutlineStyle, OutlineTarget, PageTargetView, RenameNamedDestination, SaveMode, SaveOptions, SetNamedDestination, SiblingPosition,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: edit_bookmarks in.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let edited = edit(std::fs::read(input)?)?; std::fs::write(out.join("edit_bookmarks.pdf"), edited)?; Ok(())}
/// The document with its bookmarks edited, saved incrementally.pub(crate) fn edit(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?;
// The top of the last page, in page space (points from the page's top-left). let last = doc.page_count()?.saturating_sub(1); let top = PageTargetView::At { x: Some(0.0), y: Some(0.0), zoom: None, }; let summary = doc.destination_at(last, top)?;
let mut add = AddOutlineItem::new( None, SiblingPosition::First, "Summary", OutlineTarget::Destination(summary.clone()), ); add.style = OutlineStyle::new(None, true, false); doc.apply(vec![ Op::from(add), Op::from(SetNamedDestination::new("summary", summary)), ])?;
// Rename a destination, if the file has it: bookmarks and links that use it follow. if doc.named_destinations()?.iter().any(|d| d.name == "chapter-2") { doc.apply(vec![Op::from(RenameNamedDestination::new("chapter-2", "methods"))])?; }
let outline = doc.outline()?; let find = |title: &str| outline.iter().find(|n| n.title == title).map(|n| n.id.clone()); if let (Some(website), Some(chapters)) = (find("Website"), find("Chapters")) { doc.apply(vec![Op::from(MoveOutlineItem::new( website, Some(chapters), SiblingPosition::Last, ))])?; }
let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}




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.
How it works
Section titled “How it works”outline()lists every bookmark with itsid, which the bookmark edits take, its title, where it goes, its colour and style, and whether its children show.addOutlineItem(AddOutlineItemin Rust) adds a bookmark under aparent(nullfor 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 increatedOutlineItems.updateOutlineItem,moveOutlineItemanddeleteOutlineItemchange, 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 withchildren: "promote".setNamedDestinationgives a place a name, or points an existing name elsewhere.renameNamedDestinationrenames it, together with every bookmark, link and opening view of the file that uses it. Passlinks: "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.
What to change
Section titled “What to change”- A colour or style: pass
style: { color: "#c00000", bold: true, italic: false }. Leavecolorout for the viewer’s default black. - A web address: pass
target: { uri: "https://example.com" }. Only absolutehttp,httpsandmailtoaddresses are allowed; anything else,javascript:first, fails withlink-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:
deleteNamedDestinationleaves the bookmarks and links that use it alone, since removing them could lose your content. The edit’sdestinationUseslists 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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example create_contents_page -- in.pdf font.ttf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ContentsFonts, ContentsOptions, Document, Font, OpenOptions, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: create_contents_page in.pdf font.ttf [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); let font = PathBuf::from(args.next().ok_or(usage)?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let edited = add_contents(std::fs::read(input)?, std::fs::read(font)?)?; std::fs::write(out.join("create_contents_page.pdf"), edited)?; Ok(())}
/// `bytes` 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.pub(crate) fn add_contents(bytes: Vec<u8>, font: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let options = ContentsOptions::new().with_bookmark(true); let fonts = ContentsFonts::new().with_font(Font::from_bytes(font)?); doc.create_contents_page(&options, &fonts)?; Ok(doc.save(&SaveOptions::new())?.bytes)}





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.
How it works
Section titled “How it works”- 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
TOCelement with aTOCIfor 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 withno-bookmarks. - It’s one edit: one undo removes the page, its links and its bookmark.
What to change
Section titled “What to change”- 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_atin 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 withinvalid-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 withmissing-glyph.
Next: edit the bookmarks the page is made from.
Add links
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:
// Add links to a page: one on a box drawn over a chart, one on a line of text, then point the first somewhere else.// The boxes are in page space (points from the page's top-left), as a viewer reports a drawn box// and a text selection. Each link gets a description, which screen readers read. In a tagged// document the link on text joins the structure tree around the words it covers.import { Document } from "@laminapdf/sdk";
/** The document with two links added to its first page, saved incrementally. Needs `init({ extract: true })`. */export function addLinks(bytes: Uint8Array): Uint8Array<ArrayBuffer> { using doc = Document.open(bytes);
// A box drawn over the chart. const onChart = doc.linkOnArea(0, [56, 140, 300, 240], { uri: "https://example.com/sales" }); onChart.contents = "Sales figures";
// The line "Widgets sold out in May.", as a selection gives it. const onText = doc.linkOnText(0, [[56, 358.241, 196.335, 373.223]], { uri: "https://example.com/widgets" }); onText.contents = "Widget stock";
const added = doc.apply([ { op: "addLink", args: onChart }, { op: "addLink", args: onText }, ]);
// The new links' IDs come back with the edit: change the first one's address. const chartLink = added.createdAnnotations[0]; if (chartLink !== undefined) { doc.apply([{ op: "updateLink", args: { link: chartLink, target: { uri: "https://example.com/sales/2026" } } }]); }
return doc.save({ mode: "incremental" });}//! Add links to a page: one on a box drawn over a chart, one on a line of text, then point the first somewhere else.//!//! The boxes are in page space (points from the page's top-left), as a viewer reports a drawn//! box and a text selection. Each link gets a description, which screen readers read. In a//! tagged document the link on text joins the structure tree around the words it covers.//!//! ```sh//! cargo run -p laminapdf --features extract --example add_links -- in.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, Op, OpenOptions, OutlineTarget, Pt, RectPt, SaveMode, SaveOptions, UpdateLink};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: add_links in.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let edited = add(std::fs::read(input)?)?; std::fs::write(out.join("add_links.pdf"), edited)?; Ok(())}
/// The document with two links added to its first page, saved incrementally.pub(crate) fn add(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; // These boxes fit the example's input, the quarterly report; for your own file, take them // from your viewer's drawn box and selection, or from `page_text`'s lines. let points = |x0, y0, x1, y1| RectPt::new(Pt::new(x0), Pt::new(y0), Pt::new(x1), Pt::new(y1));
// A box drawn over the chart. let chart = points(56.0, 140.0, 300.0, 240.0); let mut on_chart = doc.link_on_area(0, chart, OutlineTarget::Uri("https://example.com/sales".into()))?; on_chart.contents = Some("Sales figures".into());
// The line "Widgets sold out in May.", as a selection gives it. let line = points(56.0, 358.241, 196.335, 373.223); let mut on_text = doc.link_on_text(0, &[line], OutlineTarget::Uri("https://example.com/widgets".into()))?; on_text.contents = Some("Widget stock".into());
let added = doc.apply(vec![Op::from(on_chart), Op::from(on_text)])?;
// The new links' IDs come back with the edit: change the first one's address. if let Some(chart_link) = added.created_annotations.first() { let mut update = UpdateLink::new(chart_link.clone()); update.target = Some(OutlineTarget::Uri("https://example.com/sales/2026".into())); doc.apply(vec![Op::from(update)])?; }
let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}


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.
How it works
Section titled “How it works”linkOnAreatakes one box, andlinkOnTexttakes 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,
linkOnTextalso 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. contentsis 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.updateLinktakes that ID to change a link’s boxes, target or description, anddeleteLinkremoves it.pageLinkslists the IDs of the links a page already has.
What to change
Section titled “What to change”- 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 absolutehttp,httpsandmailtoaddresses are allowed. Any other address, such as ajavascript:one, fails withlink-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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --features extract --example mark_up -- in.pdf <time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ AnnotColor, AnnotCommon, Document, MarkupKind, NoteIcon, Op, OpenOptions, PdfDate, PointPt, Pt, RectPt, SaveMode, SaveOptions,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: mark_up in.pdf <time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); // When the marks were made, which your app takes from its clock. let at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let marked = mark_up(std::fs::read(input)?, at)?; std::fs::write(out.join("mark_up.pdf"), marked)?; Ok(())}
// 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, or from// `page_text`'s lines./// The line "Widgets sold out in May.", as a selection gives it: `[x0, y0, x1, y1]`.const WIDGETS_LINE: [f64; 4] = [56.0, 358.241, 196.335, 373.223];/// The words "sold out" on that line.const SOLD_OUT: [f64; 4] = [114.902, 358.241, 156.713, 373.223];/// The note's spot, right of the chart.const BESIDE_CHART: [f64; 2] = [310.0, 140.0];/// The colour of a paper sticky note.const STICKY_YELLOW: AnnotColor = AnnotColor::Rgb(1.0, 0.82, 0.0);
/// The document with a highlight, a note and a proposed word on its first page, saved/// incrementally.pub(crate) fn mark_up(bytes: Vec<u8>, at: PdfDate) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let mut by_me = AnnotCommon::default(); by_me.author = Some("Ada Lovelace".into()); by_me.created = Some(at); by_me.modified = Some(at);
// In a tagged document the highlight's description is already the marked text; add who // made it. let mut highlight = doc.mark_text(0, MarkupKind::Highlight, &[area(WIDGETS_LINE)])?; sign(&mut highlight.common, &by_me);
let [x, y] = BESIDE_CHART; let spot = PointPt::new(Pt::new(x), Pt::new(y)); let mut note = doc.note_at(0, spot, "Add June's figures?", NoteIcon::Comment)?; sign(&mut note.common, &by_me); note.common.color = Some(STICKY_YELLOW);
doc.apply(vec![Op::from(highlight), Op::from(note)])?;
// "sold out" reads better as "ran out": a strike-out and a caret, applied as one undo step. doc.replace_text(0, &[area(SOLD_OUT)], "ran out", by_me)?;
let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}
/// A box in page space from its corners.fn area([x0, y0, x1, y1]: [f64; 4]) -> RectPt { RectPt::new(Pt::new(x0), Pt::new(y0), Pt::new(x1), Pt::new(y1))}
/// Records on a mark who made it and when, from `by`.fn sign(common: &mut AnnotCommon, by: &AnnotCommon) { common.author.clone_from(&by.author); common.created.clone_from(&by.created); common.modified.clone_from(&by.modified);}


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”.
How it works
Section titled “How it works”markTexttakes one box per line of the selected text and a kind:highlight,underline,strikeOutorsquiggly. 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. noteAtputs 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.replaceTextgroups 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.
What to change
Section titled “What to change”- Another mark: pass
"underline","strikeOut"or"squiggly"tomarkText. - A colour or opacity: set
common.color([r, g, b]from 0 to 1) andcommon.opacitybefore applying the edit. - A note’s icon: pass
"note","comment","key","help","paragraph","newParagraph"or"insert". - Change a mark later:
updateAnnottakes the ID fromcreatedAnnotationsand a newcolor,opacityorspec. Lamina PDF draws the mark again.deleteAnnotremoves 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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --features extract --example review_comments -- marked.pdf <time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{AddReply, Document, Op, OpenOptions, PdfDate, ReviewState, SaveMode, SaveOptions, SetReviewState};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: review_comments marked.pdf <time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); // When the review was answered, which your app takes from its clock. let at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let answered = review(std::fs::read(input)?, at)?; std::fs::write(out.join("review_comments.pdf"), answered)?; Ok(())}
/// Who answers the review.const ME: &str = "Grace Hopper";
/// The document with a reply to every note that asks a question, and every highlight marked/// done, saved incrementally.pub(crate) fn review(bytes: Vec<u8>, at: PdfDate) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let mut ops = Vec::new(); for thread in doc.comment_threads(None)? { let id = thread.comment.id.parse()?; let asks = thread.comment.contents.as_deref().is_some_and(|c| c.ends_with('?')); if thread.comment.subtype == "Text" && asks { let mut reply = AddReply::new(id, "June's figures are in the appendix."); reply.author = Some(ME.into()); reply.created = Some(at); ops.push(Op::from(reply)); } else if thread.comment.subtype == "Highlight" && thread.review.as_deref() != Some("Completed") { // `quoted` is the text the highlight marks, for a list of what was checked. let mut done = SetReviewState::new(id, ReviewState::Completed); done.author = Some(ME.into()); done.created = Some(at); ops.push(Op::from(done)); } } // Every answer is one undo step. doc.apply(ops)?; let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}


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.
How it works
Section titled “How it works”- 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
reviewis its latestReviewstatus, 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.
quotedis 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.
What to change
Section titled “What to change”- 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 asmarked. - 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:
updateAnnotchanges 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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --features extract --example exchange_comments -- report.pdf reply.xfdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ CommentFormat, Document, ExportCommentsOptions, ImportCommentsOptions, ImportMode, ImportWarning, OpenOptions, SaveOptions,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: exchange_comments report.pdf reply.xfdf [out-dir]"; let pdf = PathBuf::from(args.next().ok_or(usage)?); let reply = PathBuf::from(args.next().ok_or(usage)?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let bytes = std::fs::read(&pdf)?; let name = pdf .file_name() .map_or_else(String::new, |n| n.to_string_lossy().into_owned()); std::fs::write(out.join("comments.xfdf"), export_comments(bytes.clone(), &name)?)?; std::fs::write( out.join("exchange_comments.pdf"), import_comments(bytes, &std::fs::read(reply)?)?, )?; Ok(())}
/// The document's comments as XFDF, recording the file's name so an import can tell when it is/// given to another PDF.pub(crate) fn export_comments(bytes: Vec<u8>, name: &str) -> Result<Vec<u8>, Box<dyn Error>> { let doc = Document::open_bytes(bytes, OpenOptions::new())?; let mut options = ExportCommentsOptions::new(CommentFormat::Xfdf); options.file = Some(name.to_owned()); Ok(doc.export_annotations(&options)?)}
/// The document with a reviewer's XFDF or FDF comments added to its own.pub(crate) fn import_comments(bytes: Vec<u8>, xfdf: &[u8]) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let (summary, _) = doc.import_annotations(xfdf, &ImportCommentsOptions::new(ImportMode::Merge))?; eprintln!("{} comments added, {} already here", summary.added, summary.matched); // A sound, a form field's value or a comment for a missing page is left out, and said. for warning in &summary.warnings { if let ImportWarning::Skipped(skipped) = warning { eprintln!("{}: {} ({})", warning.code(), skipped.kind, skipped.cause.as_str()); } else { eprintln!("{}", warning.code()); } } Ok(doc.save(&SaveOptions::new())?.bytes)}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.
How it works
Section titled “How it works”- 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 asfile. - 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.warningsasinterchange-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 withinterchange-dtd, since a DTD can define entities that expand without end or read other files.
What to change
Section titled “What to change”- See what an import will do first:
previewImportgives 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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example fill_form_from_json -- invoice.pdf invoice.json [out-dir]//! ```
use std::error::Error;use std::fmt::Write as _;use std::path::PathBuf;
use laminapdf::{Document, FieldValue, FillOptions, OpenOptions, SaveMode, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: fill_form_from_json form.pdf invoice.json [out-dir]"; let form = PathBuf::from(args.next().ok_or(usage)?); let answers = std::fs::read_to_string(args.next().ok_or(usage)?)?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let (report, filled) = fill(std::fs::read(form)?, &answers)?; print!("{report}"); std::fs::write(out.join("fill_form_from_json.pdf"), filled)?; Ok(())}
/// The form filled from `answers`: what the result lists, each field's value after it, and the/// filled document saved after the original bytes.pub(crate) fn fill(bytes: Vec<u8>, answers: &str) -> Result<(String, Vec<u8>), Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let filled = doc.fill_form(answers, FillOptions::default())?;
let mut report = String::new(); for name in &filled.unknown { writeln!(report, "no field named {name}")?; } for refused in &filled.refused { writeln!(report, "{} refused its value ({})", refused.name, refused.code)?; } for field in doc.form()?.fields { writeln!(report, "{}: {}", field.name, shown(field.value.as_ref()))?; } let saved = doc.save(&SaveOptions::new().with_mode(SaveMode::Incremental))?; Ok((report, saved.bytes))}
fn shown(value: Option<&FieldValue>) -> String { match value { Some(FieldValue::Text(text)) => format!("{text:?}"), Some(FieldValue::Button(Some(state))) => format!("on ({state})"), Some(FieldValue::Button(None)) => "off".to_owned(), Some(FieldValue::Choice(options)) => options.join(", "), _ => "no value".to_owned(), }}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.
How it works
Section titled “How it works”- Fields are matched by their full names. A field inside another is named after both, joined by a full stop:
customer.nameis thenamefield insidecustomer.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
trueorfalse, and radio buttons take the name or export value of the choice to turn on. A list takes an array of its options.nullempties 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 inlockedand left as it is. A value its field refuses is listed inrefusedwith a code:field-value-invalidfor text longer than the field allows or an option the list doesn’t have,field-is-signaturefor 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 isdocs/schemas/form-data.schema.jsonin the@laminapdf/sdkpackage.
What to change
Section titled “What to change”- 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 withinterchange-dtd. - Save the answers for another app:
exportFormData("xfdf")orexportFormData("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 IDsformFields()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 hasxfaNotUpdated: 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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example flatten_form -- invoice.pdf invoice.json [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, FillOptions, FlattenIntent, OpenOptions, SaveMode, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: flatten_form form.pdf answers.json [out-dir]"; let form = PathBuf::from(args.next().ok_or(usage)?); let answers = std::fs::read_to_string(args.next().ok_or(usage)?)?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let flat = flatten(std::fs::read(form)?, &answers)?; std::fs::write(out.join("flatten_form.pdf"), flat)?; Ok(())}
/// The form filled from `answers`, then every field drawn into its page, as a printer would/// show it.pub(crate) fn flatten(bytes: Vec<u8>, answers: &str) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; doc.fill_form(answers, FillOptions::default())?; let edited = doc.flatten_form(None, FlattenIntent::Print)?; // A push button or radio button with no appearance of its own stays. for warning in &edited.warnings { eprintln!("{}", warning.code()); } // A full rewrite keeps only the flattened pages, not the revisions with the fields. let options = SaveOptions::new().with_mode(SaveMode::FullRewrite); Ok(doc.save(&options)?.bytes)}
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.
How it works
Section titled “How it works”- 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-untaggedwarning 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.
What to change
Section titled “What to change”- Some fields only: pass their IDs, as
formFields()lists them, instead ofundefined. 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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example check_xfa_form -- form.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, OpenOptions, RemoveXfa, SaveMode, SaveOptions, XfaKind};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: check_xfa_form form.pdf [out-dir]"; let form = PathBuf::from(args.next().ok_or(usage)?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; std::fs::write(out.join("check_xfa_form.pdf"), check(std::fs::read(form)?)?)?; Ok(())}
/// The form as it saves: without its XFA part when it is a static XFA form, unchanged otherwise.pub(crate) fn check(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; match doc.xfa()?.map(|xfa| xfa.kind) { None => eprintln!("not an XFA form"), // Only Adobe's apps lay it out: leave it as it is. Some(XfaKind::Dynamic) => eprintln!("a dynamic XFA form: open it in Adobe Acrobat"), Some(_) => { eprintln!("a static XFA form: removing its XFA part"); doc.apply(vec![RemoveXfa::new().into()])?; } } let options = SaveOptions::new().with_mode(SaveMode::FullRewrite); Ok(doc.save(&options)?.bytes)}
The saved form has the same pages and fields, and no XFA part.
How it works
Section titled “How it works”- A form is dynamic when the catalog’s
/NeedsRenderingis true, when itsconfigpacket 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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --features extract --example flatten_comments -- marked.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, FlattenIntent, FlattenScope, OpenOptions, SaveMode, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: flatten_comments marked.pdf [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let flat = flatten(std::fs::read(input)?)?; std::fs::write(out.join("flatten_comments.pdf"), flat)?; Ok(())}
/// The document with every comment drawn into its page, as a printer would show it.pub(crate) fn flatten(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let edited = doc.flatten_annotations(&FlattenScope::All, FlattenIntent::Print)?; // Marks with no picture to keep, such as a file attachment, stay as they are. for warning in &edited.warnings { eprintln!("{}", warning.code()); } // A full rewrite keeps only the flattened pages, not the revision with the comments. let options = SaveOptions::new().with_mode(SaveMode::FullRewrite); Ok(doc.save(&options)?.bytes)}


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.
How it works
Section titled “How it works”- 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-untaggedwarning 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 withannotation-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.
What to change
Section titled “What to change”- Some pages only: pass
{ pages: [0, 2] }(0-based) instead of"all". - A selection: pass
{ annotations: ids }with IDs frompageAnnotationsorcommentThreads, or apply theflattenAnnotsop 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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --example comment_summary -- reviewed.pdf font.ttf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, Font, OpenOptions, SaveOptions, SummaryOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: comment_summary reviewed.pdf font.ttf [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); let font = PathBuf::from(args.next().ok_or(usage)?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let summary = summarise(std::fs::read(input)?, std::fs::read(font)?)?; std::fs::write(out.join("comment_summary.pdf"), summary)?; Ok(())}
/// A summary of the comments on `bytes`, set in the font `font`, which the summary embeds.pub(crate) fn summarise(bytes: Vec<u8>, font: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let doc = Document::open_bytes(bytes, OpenOptions::new())?; let mut summary = doc.comment_summary(&SummaryOptions::new(Font::from_bytes(font)?))?; // A page whose fonts the file doesn't embed is listed without its drawing. let mut warnings = summary.warnings(); for warning in warnings.next_batch(warnings.remaining()) { eprintln!("{}", warning.code()); } Ok(summary.save(&SaveOptions::new())?.bytes)}
The reviewed file doesn’t change. The summary is a document of its own, unsaved until you save it.
How it works
Section titled “How it works”- 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.
What to change
Section titled “What to change”- A list without pages: pass
layout: "list"(in Rust,SummaryLayout::List), which suits a long review. - Some comments only: pass
commentswith the IDs fromcommentThreads, such as those a comments panel shows. - Less detail: pass
replies: falseorstatus: false. - Every page: pass
emptyPages: trueto 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
languagewith the language most comments are in, so screen readers read them in that language. Passwordstoo, so the summary’s own words are in it:words: { page: "Seite {label}", kinds: { Text: "Notiz" } }(in Rust,SummaryOptions::with_wordswith aSummaryWords). 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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example draw_on_page -- in.pdf <time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ AnnotColor, AnnotCommon, AnnotSpec, Border, Document, LineEnding, Op, OpenOptions, PdfDate, PointPt, Pt, RectPt, SaveMode, SaveOptions, ShapeKind,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: draw_on_page in.pdf <time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); // When the marks were drawn, which your app takes from its clock. let at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let drawn = draw_on_page(std::fs::read(input)?, at)?; std::fs::write(out.join("draw_on_page.pdf"), drawn)?; Ok(())}
// 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: [f64; 4] = [48.0, 317.0, 340.0, 338.0];/// From the empty space right of the chart to its right edge: `[x, y]` each.const ARROW: [[f64; 2]; 2] = [[420.0, 180.0], [264.0, 200.0]];/// A wavy underline below "Total sales", as a pen traced it.const UNDERLINE: [[f64; 2]; 9] = [ [56.0, 482.0], [72.0, 478.0], [88.0, 484.0], [104.0, 478.0], [120.0, 484.0], [136.0, 478.0], [152.0, 484.0], [168.0, 478.0], [180.0, 482.0],];/// A reviewer's red pen.const RED: AnnotColor = AnnotColor::Rgb(0.85, 0.1, 0.1);
/// The document with a cloud, an arrow and an underline drawn on its first page, saved/// incrementally.pub(crate) fn draw_on_page(bytes: Vec<u8>, at: PdfDate) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let by_me = |description: &str| { let mut common = AnnotCommon::default(); common.author = Some("Ada Lovelace".into()); common.created = Some(at); common.modified = Some(at); common.color = Some(RED); common.contents = Some(description.into()); common };
let mut cloud = doc.shape_at(0, ShapeKind::Square, area(Q2_ROW))?; if let AnnotSpec::Shape(shape) = &mut cloud.spec { shape.border = Border::cloudy(1.5, 0.5); } cloud.common = by_me("Check the Q2 figures");
let [from, to] = ARROW.map(point); let mut arrow = doc.line_at(0, from, to, [LineEnding::None, LineEnding::ClosedArrow])?; if let AnnotSpec::Line(line) = &mut arrow.spec { line.border = Border::solid(2.0); line.interior = Some(RED); } arrow.common = by_me("Label the chart's axes");
let mut underline = doc.ink_at(0, &[UNDERLINE.map(point).to_vec()], 1.5)?; underline.common = by_me("Underlined: the total");
doc.apply(vec![Op::from(cloud), Op::from(arrow), Op::from(underline)])?; let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}
/// A point in page space.fn point([x, y]: [f64; 2]) -> PointPt { PointPt::new(Pt::new(x), Pt::new(y))}
/// A box in page space from its corners.fn area([x0, y0, x1, y1]: [f64; 4]) -> RectPt { RectPt::new(Pt::new(x0), Pt::new(y0), Pt::new(x1), Pt::new(y1))}


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”.
How it works
Section titled “How it works”- Each method gives an edit with a 1-point red outline and nothing filled. Change its
specbefore you apply it: the border’s width and style (solid,dashedwith a pattern, orcloudywith an intensity), theinteriorcolour that fills a shape or a closed arrowhead, and a line’sends. inkAttakes 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.
What to change
Section titled “What to change”- A circle: pass
"circle"toshapeAt. It draws the ellipse inside the box. - Another line ending:
endstakes two ofnone,square,circle,diamond,openArrow,closedArrow,butt,rOpenArrow,rClosedArrowandslash, for the start and the end. - A measured line: set the line’s
leaderto 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:
polyAtwith"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 singlewidth. - Erase a stroke:
updateAnnotwith 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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example add_text_box -- in.pdf <time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ AnnotColor, AnnotCommon, AnnotSpec, Document, Op, OpenOptions, PdfDate, PointPt, Pt, RectPt, RichText, SaveMode, SaveOptions, TextSpan,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: add_text_box in.pdf <time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); // When the boxes were typed, which your app takes from its clock. let at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let typed = add_text_box(std::fs::read(input)?, at)?; std::fs::write(out.join("add_text_box.pdf"), typed)?; Ok(())}
// 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: [f64; 4] = [330.0, 168.0, 500.0, 190.0];/// The callout's line: from the chart's right edge, through a knee, to the box.const LEADER: [[f64; 2]; 3] = [[257.0, 200.0], [300.0, 179.0], [330.0, 179.0]];/// The note beside the total.const NOTE: [f64; 4] = [300.0, 452.0, 520.0, 486.0];/// A pale yellow, like a sticky note.const YELLOW: AnnotColor = AnnotColor::Rgb(1.0, 0.96, 0.7);
/// The document with a callout and a note typed on its first page, saved incrementally.pub(crate) fn add_text_box(bytes: Vec<u8>, at: PdfDate) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let by_me = || { let mut common = AnnotCommon::default(); common.author = Some("Ada Lovelace".into()); common.created = Some(at); common.modified = Some(at); common };
let leader: Vec<PointPt> = LEADER.iter().map(|&p| point(p)).collect(); let mut callout = doc.callout_at(0, area(CALLOUT), &leader, RichText::plain("Label the chart's axes"))?; callout.common = by_me();
let text = RichText { paragraphs: vec![vec![ TextSpan::plain("Check: "), TextSpan::plain("€ 4,300").with_bold(true), TextSpan::plain(" should match the table's total."), ]], }; let mut note = doc.text_box_at(0, area(NOTE), text)?; if let AnnotSpec::FreeText(spec) = &mut note.spec { spec.fill = Some(YELLOW); } note.common = by_me();
doc.apply(vec![Op::from(callout), Op::from(note)])?; let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}
/// A point in page space.fn point([x, y]: [f64; 2]) -> PointPt { PointPt::new(Pt::new(x), Pt::new(y))}
/// A box in page space from its corners.fn area([x0, y0, x1, y1]: [f64; 4]) -> RectPt { RectPt::new(Pt::new(x0), Pt::new(y0), Pt::new(x1), Pt::new(y1))}


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.
How it works
Section titled “How it works”- Each method gives an edit for a box in 12-point Helvetica, left-aligned, with a 1-point border. Change its
specbefore you apply it: thefont,size,align, thefillbehind the text and theborder. - The text is a string, a paragraph per line, or rich text: an array of paragraphs, each an array of spans that can be
boldoritalic. 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.
What to change
Section titled “What to change”- Another font: set
spec.fontto"times"or"courier", which every reader has. For any other font, add its bytes withaddBloband setspec.fontto the ID it returns. Lamina PDF embeds the characters the box uses. - Characters the font lacks: set
spec.fallbacksto the IDs of fonts that have them, for example a Noto font for Chinese or Arabic. A character no font has fails the edit withannotation-glyph-missing. - Typewriter text: set
spec.intentto{ 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:
updateAnnotwith afreeTextpatch 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’stext. A box another app made keeps its look until you change it. Then Lamina PDF keeps its paragraphs, bold and italic, and warns withrich-text-simplifiedwhen 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 withappearance-needs-text. - A PDF/A file: Helvetica, Times and Courier aren’t embedded, which PDF/A forbids, so
doc.plan()warns withpdfa-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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example stamp_and_attach -- in.pdf <time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ AnnotCommon, AnnotSpec, AttachmentIcon, Document, DynamicStamp, Op, OpenOptions, PdfDate, PointPt, Pt, RectPt, SaveMode, SaveOptions, StampKind, StampStyle,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: stamp_and_attach in.pdf <time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); // When the report was approved, which your app takes from its clock. let at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let approved = stamp_and_attach(std::fs::read(input)?, at)?; std::fs::write(out.join("stamp_and_attach.pdf"), approved)?; Ok(())}
// 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: [f64; 4] = [370.0, 56.0, 540.0, 106.0];/// The attachment's icon, right of the table's last column.const ICON: [f64; 2] = [370.0, 282.0];/// The table's figures.const FIGURES: &str = "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.pub(crate) fn stamp_and_attach(bytes: Vec<u8>, at: PdfDate) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let by_me = || { let mut common = AnnotCommon::default(); common.author = Some("Ada Lovelace".into()); common.created = Some(at); common.modified = Some(at); common };
// The stamp's lines are written into it now and never change, as on a rubber stamp. let lines = vec!["APPROVED".to_owned(), "by Ada Lovelace".to_owned()]; let approved = StampKind::Dynamic(DynamicStamp::new(lines, StampStyle::Green)); let mut stamp = doc.stamp_at(0, area(STAMP), approved)?; stamp.common = by_me();
let mut attach = doc.attach_file_at(0, point(ICON), "figures.csv", FIGURES.as_bytes().to_vec(), "text/csv")?; if let AnnotSpec::FileAttachment(spec) = &mut attach.spec { spec.icon = AttachmentIcon::Graph; spec.file.description = Some("The table's figures".into()); spec.file.modified = Some(at); } attach.common = by_me();
doc.apply(vec![Op::from(stamp), Op::from(attach)])?; let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}
/// A point in page space.fn point([x, y]: [f64; 2]) -> PointPt { PointPt::new(Pt::new(x), Pt::new(y))}
/// A box in page space from its corners.fn area([x0, y0, x1, y1]: [f64; 4]) -> RectPt { RectPt::new(Pt::new(x0), Pt::new(y0), Pt::new(x1), Pt::new(y1))}


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.
How it works
Section titled “How it works”- A stamp shows one of three things. A standard stamp shows a name such as
approved,draftorconfidentialin 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
attachmentBytesgives 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.
What to change
Section titled “What to change”- A standard stamp: pass
{ standard: "approved" }, or another of the sixteen names, such asnotApproved,confidentialorforComment; theStampNametype lists them all. Set the edit’scommon.colorto 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 withstamp-image-invalid. - The icon: set
spec.iconto"paperclip","pushPin","graph"or"tag". Change it later withupdateAnnotand afileAttachmentpatch. - 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 withpdfa-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, sodoc.plan()warns withpdfa-font-not-embedded; use a standard stamp there. - Sound comments: older PDFs can hold recorded comments.
pageAnnotationslists them with their format and length, andsoundAsWav(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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example place_content -- in.pdf logo.png wordmark.pdf <time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ Alt, AnnotColor, ContentId, ContentLayer, Document, Op, OpenOptions, PathSpec, PdfDate, Pt, RectPt, SaveMode, SaveOptions,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: place_content in.pdf logo.png wordmark.pdf <time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); let logo = std::fs::read(args.next().ok_or(usage)?)?; let wordmark = std::fs::read(args.next().ok_or(usage)?)?; // When the report was branded, which your app takes from its clock. let at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let branded = place_content(std::fs::read(input)?, logo, wordmark, at)?; std::fs::write(out.join("place_content.pdf"), branded)?; Ok(())}
// 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: [f64; 4] = [44.0, 68.0, 551.0, 110.0];/// The logo, over the band's right end, as wide again as it is tall, as the image is.const LOGO: [f64; 4] = [455.0, 65.0, 551.0, 113.0];/// The wordmark, at the foot of the page, the size of its page.const WORDMARK: [f64; 4] = [56.0, 740.0, 176.0, 800.0];
/// The document branded: a band, a logo and a wordmark on its first page, saved incrementally.pub(crate) fn place_content( bytes: Vec<u8>, logo: Vec<u8>, wordmark: Vec<u8>, at: PdfDate,) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let id = |name: &str| ContentId::new(name).ok_or("an ID is ASCII letters, digits, '-', '_' or '.'");
// Behind the page's own content, so the title stays on top of it. let band = PathSpec::Rect { rect: area(BAND), radius: 6.0, }; let pale_blue = AnnotColor::Rgb(0.89, 0.93, 0.98); let band = doc .shape_on(0, id("title-band")?, band, Some(pale_blue), None, at)? .with_layer(ContentLayer::Behind) .with_alt(Alt::Decorative);
let logo = doc .image_at(0, id("logo")?, area(LOGO), logo, at)? .with_alt(Alt::Text("Northwind Traders".into()));
let wordmark = doc .page_at(0, id("wordmark")?, area(WORDMARK), wordmark, 0, at)? .with_alt(Alt::Text("Northwind, the company's wordmark".into()));
doc.apply(vec![Op::from(band), Op::from(logo), Op::from(wordmark)])?; let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}
/// A box in page space from its corners.fn area([x0, y0, x1, y1]: [f64; 4]) -> RectPt { RectPt::new(Pt::new(x0), Pt::new(y0), Pt::new(x1), Pt::new(y1))}


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.
How it works
Section titled “How it works”- You name each object with an ID of your own, unique on its page. Lamina PDF stores the ID with the object, so
content.updateandcontent.removefind it again after the file is saved and reopened, andcontent.addedlists 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 itwbyhpoints 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
behindlayer. 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 withcontent-needs-alt-text.
Change, fade and remove objects
Section titled “Change, fade and remove objects”- A shape: give its path as
{ line },{ rect }(with an optional cornerradius),{ ellipse }or{ polygon }, filled withfill, outlined withstroke, or both. A stroke’sdashis"solid","dashed"or"dotted". - Move, resize or turn an object later:
content.update(index, id, { matrix, modified }). The same call takesopacity, an image’scrop(the part of its square that shows), a shape’sfillandstroke, and new bytes inblob. Itsorderis the object’s place among those on its layer:0sends it to the back and-1brings it to the front. - Fade it: give
opacityfrom 0 to 1. A file that claims PDF/A-1 forbids see-through objects, sodoc.plan()warns withpdfa-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 withmode: "fullRewrite"to write the file without it.
Limits
Section titled “Limits”- 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
addSourcewith its bytes and the password; only the permissions password lifts a limit. Then use the ID it returns as the object’sblob. The password stays out of the edit and out of the saved file. Seeowner-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:
// 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" });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example add_text -- in.pdf latin.ttf arabic.ttf <time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ AnnotFont, ContentId, Document, Op, OpenOptions, PdfDate, Pt, RectPt, SaveMode, SaveOptions, StandardFamily, TextSpan,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: add_text in.pdf latin.ttf arabic.ttf <time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); let latin = std::fs::read(args.next().ok_or(usage)?)?; let arabic = std::fs::read(args.next().ok_or(usage)?)?; // When the text was typed, which your app takes from its clock. let at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let typed = add_text(std::fs::read(input)?, latin, arabic, at)?; std::fs::write(out.join("add_text.pdf"), typed)?; Ok(())}
// 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: [f64; 4] = [56.0, 690.0, 300.0, 712.0];/// The greeting, under the note.const GREETING: [f64; 4] = [56.0, 718.0, 300.0, 746.0];/// The size of the greeting, in points.const GREETING_SIZE: f64 = 16.0;
/// The document with a note and a greeting typed on its first page, saved incrementally.pub(crate) fn add_text( bytes: Vec<u8>, latin: Vec<u8>, arabic: Vec<u8>, at: PdfDate,) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let id = |name: &str| ContentId::new(name).ok_or("an ID is ASCII letters, digits, '-', '_' or '.'");
let helvetica = AnnotFont::Standard(StandardFamily::Helvetica); let runs = vec![TextSpan::plain("Reviewed "), TextSpan::plain("twice").with_bold(true)]; let note = doc .text_at(0, id("note")?, area(NOTE), runs, at)? .with_fonts(vec![helvetica], 12.0);
// The first font draws the Latin, the second what the first lacks. let fonts = vec![ AnnotFont::Font(doc.add_blob(latin)), AnnotFont::Font(doc.add_blob(arabic)), ]; let hello = vec![TextSpan::plain("Hello \u{645}\u{631}\u{62d}\u{628}\u{627}")]; let greeting = doc .text_at(0, id("greeting")?, area(GREETING), hello, at)? .with_fonts(fonts, GREETING_SIZE);
doc.apply(vec![Op::from(note), Op::from(greeting)])?; let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}
/// A box in page space from its corners.fn area([x0, y0, x1, y1]: [f64; 4]) -> RectPt { RectPt::new(Pt::new(x0), Pt::new(y0), Pt::new(x1), Pt::new(y1))}


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.
How it works
Section titled “How it works”- Fonts:
fontsis 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 withaddBloband 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.addedlists it andcontent.updateandcontent.removechange it.
What to change
Section titled “What to change”- A font that forbids embedding: a font file declares in its
OS/2table whether it may be embedded. One that forbids it fails the edit withcontent-font-not-embeddable; choose another font. Bytes that aren’t a TrueType or OpenType font, such as a WOFF2 file, fail withcontent-font-invalid. - Size, colour and alignment:
sizeis in points,colora gray, RGB or CMYK array, andalignis"left","center"or"right". - Change the text later:
content.update(index, id, { text, modified })replaces the box, runs, fonts, size and colour, andmatrixmoves 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 withappearance-needs-text. - A PDF/A file: Helvetica, Times and Courier aren’t embedded, which PDF/A forbids, so
doc.plan()warns withpdfa-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:
// 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" });}//! 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.//! The font is embedded, as both standards need. 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://! [`Document::page_marks`] lists them by the IDs below.//!//! ```sh//! cargo run -p laminapdf --example add_page_marks -- in.pdf font.ttf <time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ AnnotColor, AnnotFont, ContentId, Document, MarkContent, Op, Opacity, OpenOptions, PdfDate, SaveMode, SaveOptions, Slot,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: add_page_marks in.pdf font.ttf <time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); let font = std::fs::read(args.next().ok_or(usage)?)?; // When the marks were made, which your app takes from its clock. let at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let marked = add_page_marks(std::fs::read(&input)?, font, "archive.pdf", "27 Nov 2026", at)?; std::fs::write(out.join("add_page_marks.pdf"), marked)?; Ok(())}
/// 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. `file` and `date` are what the/// header's `{file}` and `{date}` stand for, as you want them written.pub(crate) fn add_page_marks( bytes: Vec<u8>, font: Vec<u8>, file: &str, date: &str, at: PdfDate,) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let fonts = vec![AnnotFont::Font(doc.add_blob(font))]; let id = |name: &str| ContentId::new(name).ok_or("an ID is ASCII letters, digits, '-', '_' or '.'"); // Every page, counted from 0. let pages: Vec<u32> = (0..doc.page_count()?).collect();
// A red CONFIDENTIAL across each page, turned 45 degrees and faint, which a reader can hide. let text = MarkContent::Text { text: "CONFIDENTIAL".into(), fonts: fonts.clone(), size: 90.0, color: Some(AnnotColor::Rgb(0.8, 0.1, 0.1)), }; let watermark = doc .watermark(&pages, id("confidential")?, text, at)? .with_opacity(Opacity::new(0.2).ok_or("an opacity is from 0 to 1")?) .with_angle(45.0) .hideable();
// The file's name and the date at the top right, and the page's number at the bottom centre: // slots in the order top left, centre, right, then bottom left, centre, right. let mut slots: [Option<String>; 6] = Default::default(); slots[2] = Some("{file} \u{b7} {date}".into()); slots[4] = Some("Page {page} of {pages}".into()); let folio = doc .header_footer(&pages, id("folio")?, slots, at)? .with_fonts(fonts.clone(), 9.0) .with_color(AnnotColor::Gray(0.35)) .with_fields(date, file);
// ACME-000101, ACME-000102 and on, at the bottom left. let numbers = doc .bates(&pages, id("bates")?, 101, Slot::BottomLeft, at)? .with_text("ACME-", 6, "") .with_fonts(fonts, 9.0);
doc.apply(vec![Op::from(watermark), Op::from(folio), Op::from(numbers)])?; let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}
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.
How it works
Section titled “How it works”- 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
angledegrees 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 withaddBlobfirst. - 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 withupdatePageMarkto 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:
startis 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 nextstart. The number is padded with zeros todigits, 6 unless you say otherwise (0 for none); a wider number is not cut. - Fonts: as for added text,
fontsis 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, andcontent.deletePageMark(pages, id)takes it off. An incremental save keeps the earlier revisions, and the mark stays in them.
What to change
Section titled “What to change”- Opacity and angle:
opacityis from 0 to 1 andanglefrom -360 to 360 degrees. - A layer a reader can hide:
hideable: trueputs 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 withpdfa-optional-content. - A different mark of the same kind:
updatePageMarktakes the new mark as{ watermark },{ background },{ headerFooter }or{ bates }; a mark of another kind fails withinvalid-op, and a page without the mark withunknown-page-mark. - Colour and margins:
coloris a gray, RGB or CMYK array, andmarginsis{ 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 withpdfa-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:
// 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 });}//! 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.//!//! ```sh//! cargo run -p laminapdf --example edit_xmp -- in.pdf <save-time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, Op, OpenOptions, PdfDate, SaveMode, SaveOptions, SetXmpProperty, XmpValue};
/// The namespace of the review properties: a URI you own, so they can't clash with anyone else's.const REVIEW: &str = "https://example.com/ns/review/1.0/";
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: edit_xmp in.pdf <save-time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); // The time of the save, which your app takes from its clock. let saved_at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let edited = edit(std::fs::read(input)?, saved_at)?; std::fs::write(out.join("edit_xmp.pdf"), edited)?; Ok(())}
/// The document with the review recorded in its XMP metadata, saved incrementally at `saved_at`.pub(crate) fn edit(bytes: Vec<u8>, saved_at: PdfDate) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?;
let reviewers = XmpValue::Seq(vec![ XmpValue::Text("Ada Lovelace".into()), XmpValue::Text("Charles Babbage".into()), ]); let edited = doc.apply(vec![ Op::from(SetXmpProperty::new( REVIEW, "review", "status", XmpValue::Text("Approved".into()), )), Op::from(SetXmpProperty::new(REVIEW, "review", "reviewers", reviewers)), Op::from(SetXmpProperty::new(REVIEW, "review", "round", XmpValue::Integer(2))), ])?; for property in &edited.declared { eprintln!( "declared {}:{} as {}", property.prefix, property.name, property.value_type ); }
let options = SaveOptions::new() .with_mode(SaveMode::Incremental) .with_metadata_date(saved_at); Ok(doc.save(&options)?.bytes)}
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.
How it works
Section titled “How it works”setXmpProperty(namespace, prefix, name, value)(SetXmpPropertyin Rust) sets one property.prefixis 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 aretext,uri,integer,real,boolean,date(a PDF date),langAlt(the same text in several languages), andseqandbag, 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
declaredlists them. - A file without XMP metadata gets it with the first property you set.
What to change
Section titled “What to change”- Remove a property:
removeXmpProperty(namespace, name). As with any removal, an incremental save keeps the old value in the file’s earlier revisions; save withmode: "fullRewrite"to drop it. - Title, authors and dates: use
setMetadata.setXmpPropertyondc:titleworks too and keeps the Info dictionary in step, but only with the value type the field needs: text for the title, aseqof text for the authors. - Structures and comments: read the metadata with
xmpPacket(), change its XML, and write it back withreplaceXmpPacket(xml). XML that doesn’t parse is refused withinvalid-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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --example organise_pages -- in.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ DeletePages, Document, InsertBlankPages, MovePages, Op, OpenOptions, PagePosition, PageSize, ReferenceOutcome, RotatePages, Rotation, SaveOptions,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: organise_pages in.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let organised = organise(std::fs::read(input)?)?; std::fs::write(out.join("organise_pages.pdf"), organised)?; Ok(())}
/// 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.pub(crate) fn organise(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let ids: Vec<_> = doc.page_infos()?.into_iter().map(|page| page.id).collect(); let (Some(third), Some(last)) = (ids.get(2), ids.last()) else { return Err("the document needs at least three pages".into()); }; let edited = doc.apply(vec![ Op::from(DeletePages::new(vec![third.clone()])), Op::from(MovePages::new(vec![last.clone()], PagePosition::Start)), Op::from(InsertBlankPages::new(PagePosition::End, 1, PageSize::LETTER)), Op::from(RotatePages::turn( ids.iter().take(2).cloned().collect(), Rotation::Clockwise90, )), ])?; for reference in &edited.references { if let ReferenceOutcome::Retargeted { to } = &reference.outcome { eprintln!("{:?} now points to page {to}", reference.kind); } } Ok(doc.save(&SaveOptions::new())?.bytes)}





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.
How it works
Section titled “How it works”doc.pageslists the pages in order, each with itsid. A page keeps its ID when it moves, and a new blank page gets a new one.deletePages(DeletePagesin 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’sreferenceslists 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) withmode: "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.applyruns the steps in order as one edit: if one fails, none of them apply, and oneundo()reverts them all. The edit’spageOrderlists the page IDs in their new order.
What to change
Section titled “What to change”- Remove what pointed at a deleted page: pass
references: "remove"todeletePages. 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:
reversePageswith 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, anddoc.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-leftand 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:
// 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();}//! 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 a signature's widget, which isn't copied.//!//! ```sh//! cargo run -p laminapdf --example duplicate_pages -- form.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, DuplicatePages, FieldOutcome, OpenOptions, PagePosition, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: duplicate_pages form.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let duplicated = duplicate(std::fs::read(input)?)?; std::fs::write(out.join("duplicate_pages.pdf"), duplicated)?; Ok(())}
/// The document with a copy of its first page added at the end.pub(crate) fn duplicate(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let first = doc.page_info(0)?.id; let edited = doc.apply(vec![DuplicatePages::new(vec![first], PagePosition::End).into()])?; for field in &edited.fields { match &field.outcome { FieldOutcome::Renamed { name, .. } => eprintln!("the copy's field is {name}"), _ => eprintln!("field {} was not copied: it is a signature", field.field), } } Ok(doc.save(&SaveOptions::new())?.bytes)}



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.
How it works
Section titled “How it works”duplicatePages(DuplicatePagesin 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’spageOrder.- 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
fieldslists 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.
What to change
Section titled “What to change”- 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
fieldslists it asnotCopied, 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
tagsIncompletelists that copy. On a file that claims PDF/UA-1, saving then warns withduplicate-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:
// 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();}//! 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`.//!//! ```sh//! cargo run -p laminapdf --example edit_objects -- in.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ ContentEdit, ContentObjectKind, Document, EditContent, Matrix, OpenOptions, PageObject, SaveOptions, StackPosition,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: edit_objects in.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let edited = edit(std::fs::read(input)?)?; std::fs::write(out.join("edit_objects.pdf"), edited)?; Ok(())}
/// The document with four objects of its first page changed.pub(crate) fn edit(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let objects = doc.content_objects(0)?; list(&objects); let page = doc.page_info(0)?.id; doc.apply(vec![EditContent::new(page, edits(&objects)?).into()])?; Ok(doc.save(&SaveOptions::new())?.bytes)}
/// Prints each object: what it draws, its box and, when it can't be moved, why.fn list(objects: &[PageObject]) { for object in objects { let read_only = match object.read_only { Some(reason) => format!(" (read-only: {})", reason.as_str()), None => String::new(), }; println!("{:?} {:?}{read_only}", object.kind, object.bounds); }}
/// The four edits, each naming its object as the list gave it.fn edits(objects: &[PageObject]) -> Result<Vec<ContentEdit>, Box<dyn Error>> { let shapes: Vec<&PageObject> = objects.iter().filter(|o| o.kind == ContentObjectKind::Path).collect(); let photo = objects .iter() .rev() .find(|o| o.kind == ContentObjectKind::Image) .ok_or("no image")?; let [square, second, line, ..] = shapes.as_slice() else { return Err("the page needs three shapes".into()); }; Ok(vec![ ContentEdit::Transform { object: square.object, matrix: half_size(square)?, }, ContentEdit::Delete { object: second.object }, ContentEdit::Transform { object: photo.object, matrix: Matrix::translate(300.0, 0.0), }, ContentEdit::Reorder { object: line.object, to: StackPosition::Back, }, ])}
/// Half size, about the object's centre. Page space: points from the top-left, y down.fn half_size(object: &PageObject) -> Result<Matrix, Box<dyn Error>> { let bounds = object.bounds.ok_or("the object draws nothing")?; let (cx, cy) = ( f64::midpoint(bounds.x0.get(), bounds.x1.get()), f64::midpoint(bounds.y0.get(), bounds.y1.get()), ); Ok(Matrix::translate(-cx, -cy) .then(&Matrix::scale(0.5, 0.5)) .then(&Matrix::translate(cx, cy)))}
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.
How it works
Section titled “How it works”content.objects(index)(content_objectsin 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
transformtakes 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.
What to change
Section titled “What to change”- 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:
totakes"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 withcontent-not-editable, and nothing changes. - Clipping objects: an object that clips what follows it can’t be moved or deleted; its
readOnlysaysclipping-path. - Private content: a deleted object stays in the file’s earlier revisions until a full save. The edit’s
stillInEarlierRevisionssays so; save withmode: "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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --example edit_text -- in.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ContentTextRun, Document, EditText, OpenOptions, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: edit_text in.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let edited = edit(std::fs::read(input)?)?; std::fs::write(out.join("edit_text.pdf"), edited)?; Ok(())}
/// The document with "world" rewritten on its first page.pub(crate) fn edit(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let runs = doc.text_runs(0)?; list(&runs); let run = runs .iter() .find(|r| r.read_only.is_none() && r.text.contains("world")) .ok_or("no editable run says \"world\"")?; let page = doc.page_info(0)?.id; let text = run.text.replace("world", "Lamina PDF"); doc.apply(vec![EditText::new(page, run.run, text).into()])?; Ok(doc.save(&SaveOptions::new())?.bytes)}
/// Prints each run: its line, text, font and, when it can't be edited, why.fn list(runs: &[ContentTextRun]) { for run in runs { let read_only = match run.read_only { Some(reason) => format!(" (read-only: {})", reason.as_str()), None => String::new(), }; println!( "line {}: {:?} in {} {}{read_only}", run.line, run.text, run.font_name, run.font_size ); }}
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.
How it works
Section titled “How it works”content.textRuns(index)(text_runsin 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. Itstexthas 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.
What to change
Section titled “What to change”- Delete a run: give it empty text.
- Change part of a run: name a smaller range of its glyphs,
starttoend. 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 apage, the glyphs the match covers (a run name withstartandendset to the match) and its newtext. It is all or nothing, so calldoc.content.planReplaceText(edits)first: it lists each match’s report, or theerrorthat 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’sreadOnlysays why, and editing it fails withcontent-not-editable. - Private content: the old text stays in the file’s earlier revisions until a full save. The edit’s
stillInEarlierRevisionssays so; save withmode: "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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --example style_text -- in.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{AnnotColor, Document, OpenOptions, SaveOptions, SetTextStyle, TextRunRef};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: style_text in.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let styled = style(std::fs::read(input)?)?; std::fs::write(out.join("style_text.pdf"), styled)?; Ok(())}
/// The document with "world" made bold, red and underlined on its first page.pub(crate) fn style(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let runs = doc.text_runs(0)?; let found = runs .iter() .find(|r| r.read_only.is_none() && r.text.contains("world")) .ok_or("no editable run says \"world\"")?; // The run's glyphs are numbered from `run.start`; the word is five of them. let at = u32::try_from(found.text.find("world").ok_or("no \"world\"")?)?; let word = TextRunRef::new(found.run.object, found.run.start + at, found.run.start + at + 5); let mut style = SetTextStyle::new(doc.page_info(0)?.id, vec![word]); style.bold = Some(true); style.color = Some(AnnotColor::Rgb(0.8, 0.0, 0.0)); style.underline = Some(true); doc.apply(vec![style.into()])?; Ok(doc.save(&SaveOptions::new())?.bytes)}
In the result, “Hello, world!” keeps its size and position; only “world” changes, and “!” follows it.
How it works
Section titled “How it works”- A style names runs, as editing text does, or glyphs inside a run. Each field is optional and changes only what it names.
fontis"helvetica","times","courier"or the ID of a font’s bytes fromaddBlob. 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.boldanditalicpick 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) takesbold: trueanyway. 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: trueshears the run by 12 degrees, unless the name already says italic or oblique. A run with a text rise can’t take it.bold: falseanditalic: falseare refused on such a font, since neither can be taken off. sizeis in points.baselineraises or lowers a run at 65 % of its size.underlinedraws 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.alignandlineSpacingmove 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.
When the font lacks a character
Section titled “When the font lacks a character”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, andfidelitysays"substituted". planEditTextsays which characters and which font before you commit, so a font never changes silently. The edit’stextEditsreport the same afterwards, withgrewBy, 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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --example edit_tagged_pdf -- pdf_ua_report.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, EditText, OpenOptions, RemoveConformanceClaims, SaveOptions, SetAlt};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: edit_tagged_pdf pdf_ua_report.pdf [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let edited = edit(std::fs::read(input)?)?; std::fs::write(out.join("edit_tagged_pdf.pdf"), edited)?; Ok(())}
/// The report with its summary deleted, its table's heading renamed and its chart described anew,/// saved with the claims it still meets.pub(crate) fn edit(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let page = doc.page_info(0)?.id; let runs = doc.text_runs(0)?; let summary = runs .iter() .find(|r| r.text.starts_with("Sales grew")) .ok_or("no summary")?; let heading = runs.iter().find(|r| r.text == "Sales by quarter").ok_or("no heading")?; // 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.apply(vec![ EditText::new(page.clone(), heading.run, "Quarterly sales".into()).into(), // Empty text deletes the run, and the paragraph it was. EditText::new(page, summary.run, String::new()).into(), ])?;
// 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. let chart = doc .content_objects(0)? .into_iter() .find(|o| o.alt.is_some()) .ok_or("no chart")?; let alt = "Bar chart of quarterly sales: 120, 135, 160 and 150 thousand euros."; doc.apply(vec![SetAlt::new(doc.page_info(0)?.id, chart.object, alt).into()])?;
let options = SaveOptions::new(); let mut remove = RemoveConformanceClaims::new(); for warning in &doc.plan(&options)?.conformance_warnings { // A `pdfa-…` code (and `imported-pdfa-unchecked`) breaks the PDF/A claim; the others, // the PDF/UA claim. let code = warning.code(); eprintln!("the edits broke a claim: {code}"); remove = if code.contains("pdfa") { remove.pdfa() } else { remove.pdfua() }; } if remove != RemoveConformanceClaims::new() { doc.apply(vec![remove.into()])?; } Ok(doc.save(&options)?.bytes)}
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.
How tags follow your edits
Section titled “How tags follow your edits”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 (
ActualTextorAlt) 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, anddoc.content.objects()reports the text an object’s figure has now asalt. 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-altuntil the figure has new text.
Check the claims before you save
Section titled “Check the claims before you save”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 withxmp-claim-read-only. An incremental save keeps the old claim in the file’s earlier revisions; save withmode: "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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --example crop_pages -- in.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{CropMargins, CropPages, Document, OpenOptions, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: crop_pages in.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let cropped = crop(std::fs::read(input)?)?; std::fs::write(out.join("crop_pages.pdf"), cropped)?; Ok(())}
/// The document with 36 points cropped from each side of every page.pub(crate) fn crop(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let pages = doc.page_infos()?.into_iter().map(|page| page.id).collect(); let edited = doc.apply(vec![CropPages::new(pages, CropMargins::all(36.0)).into()])?; for page in &edited.cropped_content_remains { eprintln!("page {page} hides content that is still in the file"); } Ok(doc.save(&SaveOptions::new())?.bytes)}




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.
How it works
Section titled “How it works”cropPages(CropPagesin Rust) sets each page’s crop box: the part of the page a reader shows and prints. It takestop,right,bottomandleftin 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
croppedContentRemainslists 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.
What to change
Section titled “What to change”- Set a box exactly:
setPageBoxes(SetPageBoxesin Rust) writes any of a page’s five boxes in the page’s own coordinates:media(the paper),crop,bleed,trimandart.nullremoves 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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --example resize_pages -- in.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, OpenOptions, PageSize, ResizePages, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: resize_pages in.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let resized = resize(std::fs::read(input)?)?; std::fs::write(out.join("resize_pages.pdf"), resized)?; Ok(())}
/// The document with every page on Letter paper, its content scaled to fit.pub(crate) fn resize(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let pages = doc.page_infos()?.into_iter().map(|page| page.id).collect(); doc.apply(vec![ResizePages::scale(pages, PageSize::LETTER).into()])?; Ok(doc.save(&SaveOptions::new())?.bytes)}


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.
How it works
Section titled “How it works”resizePages(ResizePagesin 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.
What to change
Section titled “What to change”- Keep the content’s size: pass
{ mode: "extend", anchor: "topLeft" }(ResizePages::extendin 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.
Copy a page in
Section titled “Copy a page in”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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --example insert_pages -- form.pdf other.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, FieldOutcome, InsertPagesFrom, OpenOptions, PagePosition, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: insert_pages form.pdf other.pdf [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); let other = PathBuf::from(args.next().ok_or(usage)?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let combined = insert(std::fs::read(input)?, std::fs::read(other)?)?; std::fs::write(out.join("insert_pages.pdf"), combined)?; Ok(())}
/// `bytes` with the third page of `other` added at the end.pub(crate) fn insert(bytes: Vec<u8>, other: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let source = doc.add_source(other, None)?; let third = doc .source_pages(&source)? .into_iter() .nth(2) .ok_or("the other file has no third page")?; let insert = InsertPagesFrom::new(source, vec![third], PagePosition::End); let edited = doc.apply(vec![insert.into()])?; for field in &edited.fields { if let FieldOutcome::Renamed { name, .. } = &field.outcome { eprintln!("a copied field was renamed {name}"); } } eprintln!("{} links removed", edited.links_removed.len()); Ok(doc.save(&SaveOptions::new())?.bytes)}



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.
Make a new PDF from pages
Section titled “Make a new PDF from pages”extractPages (extract_pages in Rust) takes page IDs and returns a new document holding only those pages:
// 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();}//! 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).//!//! ```sh//! cargo run -p laminapdf --example extract_pages -- book.pdf [out-dir]//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, OpenOptions, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: extract_pages book.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let part = extract(std::fs::read(input)?)?; std::fs::write(out.join("extract_pages.pdf"), part)?; Ok(())}
/// A new document of the third to the fifth page of `bytes`.pub(crate) fn extract(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let doc = Document::open_bytes(bytes, OpenOptions::new())?; let pages: Vec<_> = doc.page_infos()?.into_iter().skip(2).take(3).map(|p| p.id).collect(); let mut part = doc.extract_pages(&pages)?; Ok(part.save(&SaveOptions::new())?.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.
How it works
Section titled “How it works”- 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
linksRemovedlists the page that held it. - Form fields keep their names. A name the document already uses gets the next free number,
<name>#2and on, and the edit’sfieldslists each renamed field. - A signature’s field isn’t copied, since a signature signs one place in one file. The edit’s
fieldslists it asnotCopied. - Page labels continue the numbering where the copies land, and every other page keeps its label.
What to change
Section titled “What to change”- 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, andsplitcuts 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’sstructureRenamedlists it. Copied into an untagged document, the page comes without its tags, and the edit’stagsDroppedlists it. On a file that claims PDF/UA-1, copying from a file without that claim warns withimported-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.
Merge files into one
Section titled “Merge files into one”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:
// 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();}//! 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.//!//! ```sh//! cargo run -p laminapdf --example merge_documents -- a.pdf b.pdf [out-dir]//! ```
use std::error::Error;use std::path::{Path, PathBuf};
use laminapdf::{Document, MergeInput, MergeOptions, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let args: Vec<PathBuf> = std::env::args().skip(1).map(PathBuf::from).collect(); let [first, second, rest @ ..] = args.as_slice() else { return Err("usage: merge_documents a.pdf b.pdf [out-dir]".into()); }; let out = rest.first().cloned().unwrap_or_else(|| "target/examples-out".into()); std::fs::create_dir_all(&out)?; let files = [ (name(first), std::fs::read(first)?), (name(second), std::fs::read(second)?), ]; std::fs::write(out.join("merge_documents.pdf"), merge(files.to_vec())?)?; Ok(())}
fn name(path: &Path) -> String { path.file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default()}
/// One document of `files` (each a name and its bytes), in order, with a bookmark per file.pub(crate) fn merge(files: Vec<(String, Vec<u8>)>) -> Result<Vec<u8>, Box<dyn Error>> { let inputs = files .into_iter() .map(|(name, bytes)| MergeInput::new(bytes).with_title(name)) .collect(); let mut merged = Document::merge(inputs, MergeOptions::default())?; Ok(merged.save(&SaveOptions::new())?.bytes)}






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 a file by chapter
Section titled “Split a file by chapter”split cuts a document where each top-level bookmark’s page begins and returns one new document per chapter:
// 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(); }}//! 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.//!//! ```sh//! cargo run -p laminapdf --example split_document -- book.pdf [out-dir]//! ```
use std::error::Error;use std::num::NonZeroUsize;use std::path::PathBuf;
use laminapdf::{Document, OpenOptions, SaveOptions, SplitBy};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: split_document book.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; for (i, part) in split(std::fs::read(input)?)?.into_iter().enumerate() { std::fs::write(out.join(format!("split_document-{}.pdf", i + 1)), part)?; } Ok(())}
/// One file per chapter of `bytes`: a part from each top-level bookmark's page to the next.pub(crate) fn split(bytes: Vec<u8>) -> Result<Vec<Vec<u8>>, Box<dyn Error>> { let doc = Document::open_bytes(bytes, OpenOptions::new())?; let chapters = doc.split(&SplitBy::Bookmarks { level: NonZeroUsize::MIN, })?; let mut files = Vec::with_capacity(chapters.len()); for mut chapter in chapters { files.push(chapter.save(&SaveOptions::new())?.bytes); } Ok(files)}




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.
How it works
Section titled “How it works”- 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
passwordbeside its bytes. - A part of a split holds only what its pages use, as a document from
extractPagesdoes.
Merge tagged PDFs
Section titled “Merge tagged PDFs”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.
What to change
Section titled “What to change”- 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 calldoc.mergeDocuments([a.id, b.id], "end"). The edit’srenamedDestinationslists each renamed destination, and oneundo()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’sbookmarksDroppedcounts 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:
// 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 ?? [] };}//! 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.//!//! ```sh//! cargo run -p laminapdf --features extract --example extract_markdown -- <file.pdf> [out-dir]//! # writes <out-dir>/<file>.md, <file>.json and <file>.chunks.jsonl//! ```
use std::error::Error;use std::path::{Path, PathBuf};
use laminapdf::extract::{ChunkOptions, ExtractOptions, MarkdownOptions, chunks_jsonl};use laminapdf::{Document, OpenOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: extract_markdown <file.pdf> [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let stem = input.file_stem().and_then(|s| s.to_str()).unwrap_or("document"); write_outputs(&std::fs::read(&input)?, &out, stem)}
/// Writes the Markdown, the JSON and the chunks of `bytes` into `out`.pub(crate) fn write_outputs(bytes: &[u8], out: &Path, stem: &str) -> Result<(), Box<dyn Error>> { let doc = Document::open_bytes(bytes.to_vec(), OpenOptions::new())?; let extraction = doc.extract(&ExtractOptions::new())?;
// Page markers let a reader cite the page a passage came from. let markdown = extraction.to_markdown(&MarkdownOptions::new().with_page_markers(true)); std::fs::write(out.join(format!("{stem}.md")), &markdown.text)?;
// About 400 tokens a chunk, starting a new one at each heading. let chunks = extraction.chunks(&markdown, &ChunkOptions::new().with_max_tokens(400)); std::fs::write(out.join(format!("{stem}.chunks.jsonl")), chunks_jsonl(&chunks))?;
let json = doc.extract_json(&extraction, &markdown, Some(chunks)); std::fs::write(out.join(format!("{stem}.json")), json)?; Ok(())}<!-- page 1 --> # Invoice 42 Acme Widgets Ltd · 1 Example Street · London | Widgets, blue (W-100) | 3 | € 36.00 | | --- | --- | --- | | Gadget with fine-tuned dials | 1 | € 79.90 | | Café-grade sprockets | 12 | € 15.00 | | Delivery | 1 | € 4.50 | Total € 135.40
Run the Rust program on any PDF: cargo run -p laminapdf --example extract_markdown -- report.pdf out.
How it works
Section titled “How it works”Extraction starts from each page's text runs. It sets aside runs a reader can't see, and runs the file marks as artifacts, into dropped with their reason: invisible, off-page, tiny, clipped, low-contrast, covered or artifact. The other runs are joined into lines, and the lines into blocks: paragraphs, headings and tables. Once every page is read, it also sets aside headers, footers and page numbers that repeat across pages, as running-header, running-footer or page-number. Reading order then puts the blocks in sequence: from the file's structure tree when it is tagged and the tree covers the page's text, else by cutting the page into columns. The ordered blocks become the three outputs: Markdown, the laminapdf.extract/1 JSON and chunks.
A page has a title across both columns and three blocks in each column. Extraction numbers the title 1, the left column's blocks 2 to 4 from top to bottom, and the right column's blocks 5 to 7.
extract(doc.extractin 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
confidencefrom 0 to 1. When the page’s columns could be read in more than one order, the page raises theextract-column-order-uncertainwarning 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
continuedByandcontinues, 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 thechunkoption 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 thelaminapdf.extract/1document: the pages, every block with its box in points from the top-left corner, the dropped text, the file’s warnings and the chunks.
What to change
Section titled “What to change”- 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
formatto"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
textLayerwhosestatussays 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 isocr-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)andstepdo 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:
// 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(); }); });}//! An accessible report that screen readers can follow, checked against PDF/UA-1 when it is built.
use laminapdf::{ ArtifactKind, BuildError, BuildOptions, Builder, Color, FillRule, FontHandle, LinkTarget, Metadata, PageSize, PointPt, Profile, Pt, RectPt, SaveOptions, Surface, TableScope, Tag, TagKind,};
const MARGIN: f64 = 56.0;const ROW: f64 = 18.0;const COLUMN: f64 = 144.0;const HEADER_AT: PointPt = PointPt::from_points(MARGIN, 40.0);const TITLE_BASELINE: f64 = 90.0;const TABLE_TOP: f64 = 150.0;const LINK_AT: PointPt = PointPt::from_points(MARGIN, 400.0);const CHART_LEFT: f64 = 320.0;const CHART_BASE: f64 = 360.0;const BAR_WIDTH: Pt = Pt::new(36.0);const BAR_PITCH: f64 = 50.0;const BODY: Pt = Pt::new(11.0);/// The font sizes of the title and the headings; other text is `BODY`.const SIZES: [(TagKind, Pt); 2] = [(TagKind::H1, Pt::new(22.0)), (TagKind::H2, Pt::new(15.0))];const BLUE: Color = Color::Rgb(0.12, 0.47, 0.78);const QUARTERS: [(&str, f64); 4] = [("Q1", 120.0), ("Q2", 135.0), ("Q3", 160.0), ("Q4", 150.0)];const CHART_ALT: &str = "Bar chart of sales by quarter: 120, 135, 160 and 150 thousand euros.";
fn main() -> Result<(), Box<dyn std::error::Error>> { let mut args = std::env::args().skip(1); let font = std::fs::read(args.next().ok_or("arguments: <font.ttf> [out-dir]")?)?; let out = std::path::PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; Ok(std::fs::write(out.join("pdf_ua_report.pdf"), build(font)?)?)}
pub(crate) fn build(font: Vec<u8>) -> Result<Vec<u8>, Box<dyn std::error::Error>> { let mut b = Builder::new(BuildOptions::new().with_profile(Profile::PdfUa1)); b.metadata(Metadata::default().with_title("Annual sales report 2026")); b.lang("en-GB"); let font = b.font_bytes(font)?; let mut page = b.page(PageSize::A4); draw(page.surface(), &font)?; page.finish()?; Ok(b.finish()?.save(&SaveOptions::new())?.bytes)}
/// One line of text with its baseline at `y`, as the structure element `tag`, sized by it.fn line(s: &mut Surface, font: &FontHandle, tag: impl Into<Tag>, text: &str, x: f64, y: f64) -> Result<(), BuildError> { let tag = tag.into(); let size = SIZES.iter().find(|e| e.0 == tag.kind()).map_or(BODY, |e| e.1); s.tag(tag, |s| s.text(text, font, size, PointPt::from_points(x, y)).map(drop))}
fn draw(s: &mut Surface, font: &FontHandle) -> Result<(), BuildError> { // The running header is decoration: an artifact, which screen readers skip. let header = |s: &mut Surface| s.text("Acme Widgets", font, BODY, HEADER_AT).map(drop); s.artifact(ArtifactKind::Pagination, header)?; line(s, font, TagKind::H1, "Annual sales report 2026", MARGIN, TITLE_BASELINE)?; let summary = "Sales grew in three quarters of four."; line(s, font, TagKind::P, summary, MARGIN, TITLE_BASELINE + 2.0 * ROW)?; table(s, font)?; chart(s)?; let link = LinkTarget::Uri("https://example.com/accounts".into()); s.tag(TagKind::P, |s| { let text = s.text("The full accounts", font, BODY, LINK_AT)?; text.fill(BLUE).link(link, Some("The full 2026 accounts".into())); Ok(()) })}
/// A heading and a table of the quarters, whose first row holds the columns' header cells.fn table(s: &mut Surface, font: &FontHandle) -> Result<(), BuildError> { line(s, font, TagKind::H2, "Sales by quarter", MARGIN, TABLE_TOP)?; let header = Tag::new(TagKind::TH).with_scope(TableScope::Column); s.tag(TagKind::Table, |s| { s.tag(TagKind::TR, |s| { line(s, font, header.clone(), "Quarter", MARGIN, TABLE_TOP + ROW)?; line(s, font, header.clone(), "Sales (k€)", MARGIN + COLUMN, TABLE_TOP + ROW) })?; for (row, (quarter, sales)) in (2_u8..).zip(QUARTERS) { let y = TABLE_TOP + ROW * f64::from(row); s.tag(TagKind::TR, |s| { line(s, font, TagKind::TD, quarter, MARGIN, y)?; line(s, font, TagKind::TD, &format!("{sales:.0}"), MARGIN + COLUMN, y) })?; } Ok(()) })}
/// The quarters as bars standing on the chart's base: one figure with alternate text.fn chart(s: &mut Surface) -> Result<(), BuildError> { s.tag(Tag::new(TagKind::Figure).with_alt(CHART_ALT), |s| { s.fill_color(BLUE); for (i, (_, sales)) in (0_u8..).zip(QUARTERS) { let x = CHART_LEFT + BAR_PITCH * f64::from(i); let bar = RectPt::from_xywh(Pt::new(x), Pt::new(CHART_BASE - sales), BAR_WIDTH, Pt::new(sales)); s.path(|p| _ = p.rect(bar)).fill(FillRule::NonZero); } Ok(()) })}
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.
How it works
Section titled “How it works”profiles: ["PDF/UA-1"](Profile::PdfUa1in Rust) tags the document and makesfinish()check the rules a program can check. It fails with a coded error for the first rule the report breaks; Accessible PDFs lists them.metadatagives the report its title andlangits language, which PDF/UA-1 asks for. The font is an embedded Noto Sans, because PDF/UA-1 refuses the standard 14 fonts.tagputs what its callback draws inside a structure element, such asH1,PorTD, in reading order. Thelinehelper tags one line of text and sizes it by its tag: 22 points forH1, 15 forH2, 11 for the rest.- The table’s first row holds
THheader cells with a column scope, so a screen reader can name each cell’s column. - The four bars are one
Figurewith 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 aLinkelement inside its paragraph.
What to change
Section titled “What to change”- The numbers: change
QUARTERS, then changeCHART_ALTto 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. AnLholdsLIitems or a nestedL, and anLIholds aLbland anLBody: anything else inside them failsfinish()withinvalid-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:
// 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] }), );}//! An archival letter, written as PDF/A-2b and as PDF/A-2u that is also PDF/UA-1.//!//! Run it with `cargo run -p laminapdf --example pdf_a_archive -- <font.ttf> <photo.jpg> [out-dir]`: it writes//! `pdf_a_archive-2b.pdf` and `pdf_a_archive-2u.pdf`.
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ ArtifactKind, BuildError, BuildOptions, Builder, Color, FillRule, FontHandle, Image, Metadata, PageSize, PointPt, Profile, Pt, RectPt, SaveOptions, Surface, TagKind, TextBoxOptions,};
const MARGIN: f64 = 56.0;const BAND_HEIGHT: f64 = 70.0;const TITLE_AT: PointPt = PointPt::from_points(MARGIN, 110.0);/// The top of the letter's text and of the photo beside it, and the height of both.const BLOCK_TOP: f64 = 130.0;const BLOCK_HEIGHT: f64 = 120.0;const LETTER_WIDTH: f64 = 300.0;const PHOTO_LEFT: f64 = 380.0;const PHOTO_WIDTH: f64 = 160.0;const FOOTER_AT: PointPt = PointPt::from_points(MARGIN, 300.0);const TITLE: Pt = Pt::new(22.0);const BODY: Pt = Pt::new(11.0);const BAND_OPACITY: f64 = 0.35;const PHOTO_ALT: &str = "A photograph of the sprockets, packed in a box";const LETTER: &str = "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.";
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "arguments: <font.ttf> <photo.jpg> [out-dir]"; let font = std::fs::read(args.next().ok_or(usage)?)?; let photo = std::fs::read(args.next().ok_or(usage)?)?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let a2b = build(Level::A2b, font.clone(), photo.clone())?; std::fs::write(out.join("pdf_a_archive-2b.pdf"), a2b)?; let a2u = build(Level::A2u, font, photo)?; Ok(std::fs::write(out.join("pdf_a_archive-2u.pdf"), a2u)?)}
/// Which archive to write.#[derive(Debug, Clone, Copy)]pub(crate) enum Level { /// PDF/A-2b: the letter looks the same everywhere. A2b, /// PDF/A-2u, whose text maps to Unicode, and PDF/UA-1. A2u,}
/// The letter's bytes, in `font` (a TrueType or OpenType file) with `photo` (a JPEG).pub(crate) fn build(level: Level, font: Vec<u8>, photo: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let options = match level { Level::A2b => BuildOptions::new().with_profile(Profile::PdfA2b), Level::A2u => BuildOptions::new() .with_profile(Profile::PdfA2u) .with_profile(Profile::PdfUa1), }; let mut b = Builder::new(options.with_tagged(true)); b.metadata( Metadata::default() .with_title("Order confirmation 42") .with_author("Acme Widgets Ltd"), ); b.lang("en-GB"); let font = b.font_bytes(font)?; let photo = Image::jpeg(photo)?; let mut page = b.page(PageSize::A4); draw(page.surface(), &font, &photo)?; page.finish()?; let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
fn draw(s: &mut Surface, font: &FontHandle, photo: &Image) -> Result<(), BuildError> { // A translucent band across the top: decoration, and transparency, which PDF/A-2 allows. let width = PageSize::A4.width.get(); s.artifact(ArtifactKind::Layout, |s| { s.save() .opacity(BAND_OPACITY, 1.0) .fill_color(Color::rgb(0.12, 0.47, 0.78)); s.path(|p| _ = p.rect(RectPt::from_points(0.0, 0.0, width, BAND_HEIGHT))) .fill(FillRule::NonZero); s.restore(); Ok(()) })?; s.tag(TagKind::H1, |s| { s.text("Order confirmation 42", font, TITLE, TITLE_AT).map(drop) })?; let body = RectPt::from_points(MARGIN, BLOCK_TOP, LETTER_WIDTH, BLOCK_HEIGHT); s.tag(TagKind::P, |s| { s.text_box(LETTER, font, BODY, body, &TextBoxOptions::new()).map(drop) })?; let beside = RectPt::from_points(PHOTO_LEFT, BLOCK_TOP, PHOTO_WIDTH, BLOCK_HEIGHT); s.figure(photo, beside, Some(PHOTO_ALT)); let footer = "Acme Widgets Ltd, 1 Example Street, London"; s.tag(TagKind::P, |s| s.text(footer, font, BODY, FOOTER_AT).map(drop))}


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.
How it works
Section titled “How it works”- 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
H1title,Pparagraphs 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.
textBoxbreaks the letter into lines inside its box, beside the photo. The JPEG goes into the file as it is.
What to change
Section titled “What to change”- The letter: change
LETTER.textBoxleaves out lines that don’t fit, so makeBLOCK_HEIGHTlarger for a longer letter, or passoverflow: "error"to fail withtext-overflowinstead. - The photo: pass any RGB or gray JPEG, or
Image.png(bytes)for a PNG (Image::pngin Rust). A CMYK JPEG failsfinish()withdevice-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:
// 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" }, });}//! A PDF/A-3b invoice that carries the same invoice as XML, attached for software to read.//!//! Run it with `cargo run -p laminapdf --example pdf_a3_invoice_with_xml -- <font.ttf> [out-dir]`.
use std::error::Error;use std::fmt::Write as _;use std::path::PathBuf;
use laminapdf::{ AfRelationship, Attachment, BuildError, BuildOptions, Builder, Color, FontHandle, LinkTarget, Metadata, PageSize, PointPt, Profile, Pt, SaveOptions, StrokeStyle, Surface,};
const MARGIN: f64 = 56.0;/// The page's right edge, less the margin: where the rule under the items ends.const RIGHT: f64 = PageSize::A4.width.get() - MARGIN;const AMOUNTS: f64 = 460.0;const ROW: f64 = 22.0;const TITLE_BASELINE: f64 = 80.0;const FIRST_ROW: f64 = 130.0;/// 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: f64 = 7.0;const TOTAL_DROP: f64 = 18.0;const NOTE_DROP: f64 = 68.0;/// How far left of the amounts column the total starts, to fit its "Total" label.const TOTAL_INDENT: f64 = 40.0;const TITLE: Pt = Pt::new(24.0);const TOTAL: Pt = Pt::new(14.0);const BODY: Pt = Pt::new(11.0);const ITEMS: [(&str, u32, f64); 3] = [("Sprockets", 12, 1.25), ("Gadget", 1, 79.90), ("Delivery", 1, 4.50)];
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let font = std::fs::read(args.next().ok_or("arguments: <font.ttf> [out-dir]")?)?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; Ok(std::fs::write(out.join("pdf_a3_invoice_with_xml.pdf"), build(font)?)?)}
/// The invoice's total.fn total() -> f64 { ITEMS.iter().map(|(_, qty, price)| f64::from(*qty) * price).sum()}
/// The invoice as XML, in a made-up schema (a real e-invoice follows EN 16931, as Factur-X does).fn invoice_xml() -> Result<String, std::fmt::Error> { let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<invoice number=\"42\" currency=\"EUR\">\n"); for (item, qty, price) in ITEMS { writeln!(xml, " <line item=\"{item}\" quantity=\"{qty}\" price=\"{price:.2}\"/>")?; } writeln!(xml, " <total>{:.2}</total>\n</invoice>", total())?; Ok(xml)}
/// The invoice's bytes, in `font` (a TrueType or OpenType file).pub(crate) fn build(font: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut b = Builder::new(BuildOptions::new().with_profile(Profile::PdfA3b)); b.metadata( Metadata::default() .with_title("Invoice 42") .with_author("Acme Widgets Ltd"), ); let font = b.font_bytes(font)?; let mut page = b.page(PageSize::A4); draw(page.surface(), &font)?; page.finish()?; let xml = Attachment::new("invoice-42.xml", invoice_xml()?.into_bytes(), "text/xml") .with_relationship(AfRelationship::Alternative) .with_description("Invoice 42 as XML"); b.attach(xml); let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
fn draw(s: &mut Surface, font: &FontHandle) -> Result<(), BuildError> { let at = PointPt::from_points; s.text("Invoice 42", font, TITLE, at(MARGIN, TITLE_BASELINE))?; let mut y = FIRST_ROW; for (item, qty, price) in ITEMS { s.text(&format!("{qty} × {item}"), font, BODY, at(MARGIN, y))?; let amount = f64::from(qty) * price; s.text(&format!("€ {amount:.2}"), font, BODY, at(AMOUNTS, y))?; y += ROW; } let rule = y - RULE_RISE; s.stroke_color(Color::gray(0.5)) .path(|p| _ = p.move_to(at(MARGIN, rule)).line_to(at(RIGHT, rule))) .stroke(&StrokeStyle::default()); let total_at = at(AMOUNTS - TOTAL_INDENT, y + TOTAL_DROP); s.text(&format!("Total € {:.2}", total()), font, TOTAL, total_at)?; let note = "The invoice is attached as invoice-42.xml."; let note = s.text(note, font, BODY, at(MARGIN, y + NOTE_DROP))?; let online = LinkTarget::Uri("https://example.com/invoices/42".into()); note.link(online, Some("Invoice 42 online".into())); Ok(())}
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.
How it works
Section titled “How it works”profiles: ["PDF/A-3b"](Profile::PdfA3bin 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.
invoiceXmlwrites the line items and the total from the sameITEMSthe page draws, so the PDF and the XML always agree. Its schema is made up for the recipe.attachadds the file with its name, its bytes and its MIME type,text/xml. PDF/A needs a MIME type on every attachment, orfinish()fails withembedded-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.descriptionis the text a viewer shows beside the file.
What to change
Section titled “What to change”- The items: change
ITEMS. The page, the total and the XML all follow. - A real e-invoice: replace
invoiceXmlwith 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"toprofiles, setlangand 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:
// 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 });}//! 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 (as the//! `pdf_a3_invoice_with_xml` example writes).//!//! ```sh//! cargo run -p laminapdf --example attach_factur_x -- invoice.pdf <save-time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ AfRelationship, AttachTarget, Document, Op, OpenOptions, PdfDate, SaveMode, SaveOptions, SetXmpProperty, XmpValue,};
/// The Factur-X XMP namespace and prefix (Factur-X 1.0, §6.2.2).const FX: &str = "urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0#";
/// A placeholder for the invoice's Cross Industry Invoice XML.const XML: &str = "<?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>";
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: attach_factur_x invoice.pdf <save-time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); // The time of the save, which your app takes from its clock. let saved_at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let invoice = attach(std::fs::read(input)?, saved_at)?; std::fs::write(out.join("attach_factur_x.pdf"), invoice)?; Ok(())}
/// The invoice with `factur-x.xml` attached and the Factur-X properties recorded, saved/// incrementally at `saved_at`.pub(crate) fn attach(bytes: Vec<u8>, saved_at: PdfDate) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?;
// PDF/A-3 asks every attached file for an association, a MIME type and a modification date. let mut xml = doc .attach_file("factur-x.xml", XML.as_bytes().to_vec(), "text/xml") .with_target(AttachTarget::Document, AfRelationship::Alternative); xml.description = Some("Factur-X invoice".into()); xml.modified = Some(saved_at); let fx = |name: &str, value: &str| Op::from(SetXmpProperty::new(FX, "fx", name, XmpValue::Text(value.into()))); doc.apply(vec![ Op::from(xml), fx("DocumentType", "INVOICE"), fx("DocumentFileName", "factur-x.xml"), fx("Version", "1.0"), fx("ConformanceLevel", "MINIMUM"), ])?;
let options = SaveOptions::new() .with_mode(SaveMode::Incremental) .with_metadata_date(saved_at); // An attachment that breaks the file's PDF/A level says so before the save; this one // keeps it. for warning in doc.plan(&options)?.conformance_warnings { eprintln!("{}", warning.code()); } Ok(doc.save(&options)?.bytes)}
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.
How it works
Section titled “How it works”attachFileOp(name, bytes, mime, options)keeps the bytes for the session and makes theattachFileedit;attach_filedoes the same in Rust.attachFileapplies it at once.attachTo: "document"associates the file with the whole document, andrelationship: "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
attachmentBytescompares 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()warnspdfa-attachment-forbidden: those levels allow no attached files but PDF/A ones.
What to change
Section titled “What to change”- 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 useZUGFeRD-invoice.xml. - The profile: set
ConformanceLevelto the profile your XML follows:MINIMUM,BASIC WL,BASIC,EN 16931orEXTENDED. - 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:
// 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.
How it works
Section titled “How it works”- It needs the text module,
init({ text: true }), because it draws with embedded fonts. Font.fromBytesreads each font file, andb.fontregisters both before the first page. Each font is embedded once for the whole report, with only the glyphs its 100 pages draw.s.textdraws one line, withat[1]as its baseline, ands.textBoxbreaks the paragraph into lines that fitPARAGRAPH_BOX.- In the table, the units and the revenue are text boxes as wide as their columns, with
align: "end"to right-align them.cellworks 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.metadataandlang("en-GB")set the title, author and language once for the document, andusingfrees the builder and the document when the function returns.
What to change
Section titled “What to change”- Your data: replace
unitsShippedwith your own figures, and setREPORT_PAGESandPRODUCTSto your counts. - A longer table: 20 rows end at 656 points, above the page number at 800. For more rows, lower
ROW_HEIGHTor 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
producerandcreationDateinoptions, such ascreationDate: "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:
// 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.
How it works
Section titled “How it works”- It needs only
init(): opening a file uses the base module, without fonts or text. Document.opengets the password only when you pass one, and tries it against both of the file’s passwords. See Open password-protected files.LIMITSallows 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 withlimit-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.usingfrees the document as soon as the function returns, so the WebAssembly side keeps no copy of the file.
What to change
Section titled “What to change”- Ask for the password again: on
password-requiredorwrong-password, ask your user and callopenUntrustedagain with their answer. - Name the limit: on
limit-exceeded, returne.data?.limittoo. It names the limit the file went over as Rust spells it, such asmax_stream_decodedformaxStreamDecoded. - 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: trueto the options, and a file that needs repair fails withstrictinstead 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:
// 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.
How it works
Section titled “How it works”connectstarts the Web Worker file that ships with@laminapdf/sdkand checks that it comes from the same build as your page.client.opencopies the bytes into the Web Worker and returns a remote document, whose methods return promises.await usingcloses 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
onProgresswithdone,totalandphase, 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, anderror.causeholds the signal’s reason. A save stops at its next step. client.terminate()infinallystops the Web Worker however the save ended, which also stops an open that was still running.
What to change
Section titled “What to change”- A progress bar: in
onProgress, set a<progress>element’svaluetodoneand, when the save knows it, itsmaxtototal. - Large files: pass
transfer: truetoclient.opento move the buffer instead of copying it, which leaves your copy empty. See Keep the page responsive. - Several files: call
connectonce, 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 defaultautomode. 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:
// 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.
How it works
Section titled “How it works”init({ text: true })loads the WebAssembly modules the first time an isolate runsfetch, and returns at once after that. An isolate is one running copy of the Cloudflare Worker, which serves many requests.FONTSmaps 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 fromsrc/fonts/, and that PDF embeds only the glyphs the letter uses.- An unknown path gets a 404, and a name longer than
MAX_NAMEcharacters gets a 400 before anything is drawn. isNameErrorturns two codes into a 400 with the error’s JSON.missing-glyphmeans a character the font lacks, andencoding-fullmeans more than 37 different letters outside Helvetica’s Western European set. Any other error, such as a broken font file, becomes a 500.letterfrees its builder infinally, andsaveAndFreefrees the document once its bytes are copied out, because the isolate goes on to serve other requests.
What to change
Section titled “What to change”- The document: draw your own pages in
letter, and keep bothfinallyblocks, 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 toFONTS. The quick start’s Wrangler configuration bundles every.ttfand.otffile as bytes. - Errors the caller caused: add a code to
isNameErrorwhen the request can cause it, such astext-overflowfor a text box drawn withoverflow: "error". See Errors and warnings. - A download name: add
content-disposition: attachment; filename="letter.pdf"to the headers inpdf, 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.