Read and edit PDFs, on one page
This page shows every Read and edit PDFs page in order. Read offline lists every section and the whole guide as one PDF.
Edit a PDF
You’ll open a PDF, change its title and author, and save the edit after the original bytes. You need this whenever your app changes a file someone gave it: a corrected title, a rotated scan, a report marked final.
This example generates a draft report, opens its bytes and retitles it in one transaction. Then it saves incrementally, which keeps the draft’s bytes at the start of the result, unchanged:
// 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)}
Your edits live beside the bytes you opened and never change them. Nothing reaches a file until you save. How Lamina PDF thinks about a PDF explains why it works this way.
Group edits into a transaction
Section titled “Group edits into a transaction”doc.transact(tx => …) collects edits, such as setMetadata and rotatePage, and applies them together when the callback returns. If the callback throws, none of them apply. The callback is synchronous, and editing or saving the same document inside it fails with nested-transaction.
Change the metadata
Section titled “Change the metadata”doc.setMetadata({ title, authors }) changes a document’s title, authors, subject, keywords, dates, and the creating and producing applications, and doc.removeMetadata(["keywords"]) removes fields. A PDF keeps these facts twice, in its Info dictionary and its XMP metadata, and each edit writes both. doc.metadata() reads them back. Edit the metadata has the whole program.
Organise the pages
Section titled “Organise the pages”Five calls change which pages a document has and their order: doc.deletePages(ids), doc.movePages(ids, "start"), doc.insertBlankPages("end", 1, { width: 612, height: 792 }), doc.rotatePages(ids, 90, { mode: "turn" }) and doc.reversePages(ids). They name pages by ID, and a page keeps its ID when it moves. Deleting a page sends the bookmarks and links that pointed at it to the nearest page left, and deleting every page is refused. Organise pages has the whole program.
doc.duplicatePages(ids, "end") copies pages. A copy shares its page’s content but gets annotations and form fields of its own, so filling in the copy leaves the original alone. Duplicate pages shows a form page copied.
doc.cropPages(ids, { top: 36, left: 36 }) crops pages by margins of the page as it shows, so one set suits every size and rotation, and doc.setPageBoxes(ids, { trim: [x0, y0, x1, y1] }) sets any of a page’s five boxes. A crop only hides content: the edit’s croppedContentRemains lists the pages whose hidden text is still in the file. Crop pages has the whole program.
doc.resizePages(ids, { width: 612, height: 792 }) puts pages on new paper, scaling their content to fit, and doc.setOrientation(ids, "landscape") turns pages shown the other way. Links, notes, bookmarks and the opening view move with the content. Resize pages has the whole program.
doc.addSource(bytes) opens another PDF as a source of pages. doc.insertPagesFrom(source.id, pages, "end") copies its pages in, and doc.replacePages(targets, source.id, pages) puts them in other pages’ places. doc.extractPages(ids) makes a new PDF from some pages. Copy pages between PDFs shows each.
Document.merge(files) makes one document from several files, with a bookmark for each, and doc.mergeDocuments(sources, "end") merges sources into an open document as one edit. doc.split({ bookmarks: 1 }) makes one document per chapter. A merge of tagged PDFs makes a tagged file, each file’s tags under a Part named after it. Merge and split PDFs shows both.
Name the pages
Section titled “Name the pages”A viewer’s page box can show a page’s label instead of its number: “Cover”, “iv” or “A-3”. doc.setPageLabels(ranges) replaces a document’s labels. Each range starts at a page, named by its ID, and labels that page and the ones after it until the next range. A range has a style (decimal, roman or letters, upper or lower case), a prefix and a first number. The first range must start on the first page and the rest must follow in page order, or the edit fails with invalid-label-ranges. An empty list removes the labels.
This example labels a cover, roman front matter and a numbered body:
// Give a document page labels, the names viewers show for its pages: "Cover" for the first,// lowercase roman numerals for the front matter, and numbers from 1 where the body starts.// A range names its first page by ID and labels the pages up to the next range. The edit is one// op, saved incrementally after the original bytes.import { Document } from "@laminapdf/sdk";
/** The document with a cover, roman front matter from its second page and numbers from its third. */export function pageLabels(bytes: Uint8Array): Uint8Array<ArrayBuffer> { using doc = Document.open(bytes); const [cover, contents, body] = doc.pages; if (cover === undefined || contents === undefined || body === undefined) { throw new Error("the example needs three pages or more"); }
doc.setPageLabels([ { page: cover.id, prefix: "Cover" }, { page: contents.id, style: "lowerRoman" }, { page: body.id, style: "decimal" }, ]);
// `doc.pages[i].label` now reads "Cover", "i", "1", "2", … return doc.save({ mode: "incremental" });}//! Give a document page labels, the names viewers show for its pages: "Cover" for the first,//! lowercase roman numerals for the front matter, and numbers from 1 where the body starts.//!//! A range names its first page by ID and labels the pages up to the next range. The edit is//! one op, saved incrementally after the original bytes.//!//! ```sh//! cargo run -p laminapdf --example page_labels -- in.pdf [out-dir] # a file of three pages or more//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{Document, LabelStyle, Op, OpenOptions, PageLabelRange, SaveMode, SaveOptions, SetPageLabels};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let input = PathBuf::from(args.next().ok_or("usage: page_labels in.pdf [out-dir]")?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let labelled = label(std::fs::read(input)?)?; std::fs::write(out.join("page_labels.pdf"), labelled)?; Ok(())}
/// The document with a cover, roman front matter from its second page and numbers from its/// third, saved incrementally.pub(crate) fn label(bytes: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; if doc.page_count()? < 3 { return Err("the example needs three pages or more".into()); } let [cover, contents, body] = [0, 1, 2].map(|index| doc.page_info(index).map(|page| page.id));
doc.apply(vec![Op::from(SetPageLabels::new(vec![ PageLabelRange::new(cover?, None).with_prefix("Cover"), PageLabelRange::new(contents?, Some(LabelStyle::LowerRoman)), PageLabelRange::new(body?, Some(LabelStyle::Decimal)), ]))])?;
// `doc.page_info(i)?.label` now reads "Cover", "i", "1", "2", … Ok(doc.save(&SaveOptions::new().with_mode(SaveMode::Incremental))?.bytes)}Edit what a page draws
Section titled “Edit what a page draws”doc.content.objects(index) lists the shapes, text, images and other objects a page already draws, in painting order, each with its box in page space. doc.content.hitTest(index, [x, y]) gives the objects under a point, topmost first. Then doc.content.edit(index, edits) moves, resizes, deletes, crops, replaces or reorders them in one edit, naming each object as the list gave it. Only the objects you name are written again, so the rest of the page keeps its bytes. Edit what a page draws has the whole program.
To change words rather than whole objects, doc.content.textRuns(index) lists the runs of text a page shows, and doc.content.editText(index, run, text) gives a run new text in the font it is set in. The text after the run in the same text object moves to fit, and empty text deletes the run. doc.content.setTextStyle(index, runs, style) changes a run’s font, size, colour, bold, italic, underline and baseline, and aligns and spaces its lines. Edit the text a page shows and change how text looks have the whole programs.
In a tagged PDF, these edits keep the tags up to date: deleted content leaves the structure tree, and moved or rewritten content keeps its place in it. Before saving, doc.plan().conformanceWarnings lists the PDF/A and PDF/UA claims the edits broke, and doc.removeConformanceClaims() saves without them. Edit a tagged PDF has the whole program.
Editing what a page already draws is best effort. An object that clips what follows it can’t be moved, and its readOnly says why before you try. A move in the stacking order that would make an object draw differently is refused with content-not-editable and a reason.
Undo and redo
Section titled “Undo and redo”doc.undo() reverts the last transaction as a whole, and doc.redo() applies it again. A transaction is the unit of undo, so group the edits a user would expect to undo together. A new transaction clears what redo could apply.
Both return a Reverted record, { outcome, touchedPages }, or undefined when there is nothing to undo or redo. outcome is applied, or partial when a later edit replaced part of the change, which keeps the later value, or skipped when nothing could be restored. touchedPages lists the IDs of the pages the transaction changed, so a viewer redraws only those. doc.apply(ops) returns touchedPages too, and changed, which is false when the edit only set values the document already had and so left nothing to undo.
Three transactions run in order: the first runs setInfo and rotatePage, the second rotatePage, and the third both. doc.undo() reverts the last transaction as a whole, and doc.redo() applies it again. A new transaction clears what redo could apply.
Replay edits stored as JSON
Section titled “Replay edits stored as JSON”Every edit is also a plain JSON object, such as { op: "rotatePage", args: { … } }. So you can store edits, send them to a server and replay them later. doc.apply(ops) applies a list of them as one transaction, and doc.applyLog({ v: 1, ops }) replays a saved log.
Next: save a PDF.
Save a PDF
You’ll save an edited PDF, either by appending your changes to the original bytes or by writing the whole file again. The choice matters when a file is signed, was damaged, or is password-protected, because each one limits how it can be saved.
This example, from Edit a PDF, asks for an incremental save, which keeps the original bytes at the start of the result, unchanged:
// 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)}
Choose a save mode
Section titled “Choose a save mode”Every save either appends a revision to the bytes you opened (an incremental save) or writes the whole file again (a full rewrite). You pick one with the mode option:
mode |
What it writes |
|---|---|
auto (the default) |
Incremental when that’s allowed, otherwise a full rewrite |
incremental |
The original bytes unchanged, then one appended revision |
fullRewrite |
The whole file again |
doc.save(options) returns the bytes, and doc.saveWithReport(options) also says what it wrote. doc.saveJob() does the same work in steps, so a page can save a large file without freezing. The same file with the same edits always saves to the same bytes.
An incremental save (incremental) keeps the original bytes and appends one revision after them. A signature over those bytes stays valid for the edits it allows. A full rewrite (fullRewrite) writes every byte again as one new file. Signatures over the original bytes are no longer valid, so a signed file saves this way only when you pass invalidateSignatures: true, which removes them.
When a file refuses a save
Section titled “When a file refuses a save”Every save makes a plan before it writes. The plan reads the file’s save constraint: what its signatures, permissions, repairs and encryption allow. Then it picks a mode or refuses:
- A signed file saves only incrementally, and only with edits its signatures allow. Anything else fails with
would-invalidate-signatures. PassinvalidateSignatures: trueto save anyway, which removes the broken signatures from the output. - A repaired file, one Lamina PDF had to fix as it opened, can’t safely take an appended revision. It needs a full rewrite, so asking for
incrementalfails withrequires-rewrite. - An edited encrypted file keeps its encryption: an incremental save encrypts what it appends, and a full rewrite encrypts everything again, under the key the file opened with.
doc.removeEncryption(), orremoveEncryption: true, writes a plaintext full rewrite instead, for whoever may lift the protection (otherwiseowner-password-required). - A file you protect with
setEncryptionsaves only as a full rewrite, since an incremental save would leave the earlier revisions in plain text. So does a file whose protection you remove. - An unchanged document, even a signed, repaired or encrypted one, saves incrementally in
autoandincrementalmode and returns the bytes you opened. PassingremoveEncryption: truerewrites it without its encryption instead, again only for whoever may lift the protection.
Every save plans before it writes, and an unchanged document comes first: in auto and incremental mode it saves incrementally and returns the bytes you opened, whatever else is true of it. A signed file saves incrementally, with the edits its signatures allow. Any other save fails with would-invalidate-signatures unless you pass invalidateSignatures: true, which saves anyway and removes the signatures that no longer hold. A repaired file needs a full rewrite: auto picks fullRewrite, and asking for incremental fails with requires-rewrite. An encrypted file keeps its protection in every mode. Removing it (removeEncryption: true or doc.removeEncryption()) saves as fullRewrite, and fails with owner-password-required when the file was opened with an open password that sets limits. An edited file in two of these states meets both rules: a signed file that was repaired fails until you pass invalidateSignatures: true.
See the plan before you save
Section titled “See the plan before you save”doc.plan(options) says how a save would go, without saving. Its constraint is free, appendOnly, requiresRewrite or conflict, and it lists the signatures, the edits they forbid and the refusal code a save would fail with. Show it before the user saves. To warn before an edit instead, doc.wouldViolate(op) lists what one edit would break.
Write a copy, then adopt it
Section titled “Write a copy, then adopt it”doc.saveCopy(options) writes what a save would and leaves the document as it was: its edits stay unsaved, and a later plan still sees them. Use it for Download a copy, and for a save whose write can fail, such as one to the user’s disk. Write the copy first, then call doc.adoptCopy(bytes, report.historyCleared), which makes it the document’s saved file. If the write fails, don’t adopt it: every edit stays unsaved.
Sign a file
Section titled “Sign a file”A sign edit asks for a digital signature, and two calls make it. The key never reaches Lamina PDF: a WebCrypto key, a smart card or a signing service signs the bytes in between, wherever it runs.
doc.apply([{ op: "sign", args: { target: { kind: "newField", page, rect: { x0: 0, y0: 0, x1: 0, y1: 0 }, name: "Signature1" }, params: { claimedTime: "D:20261130120000Z" } } }]); // your clock's timeconst prepared = doc.prepareSignature([certificate]); // DER, the signer's own firstconst raw = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, privateKey, prepared.toBeSigned);const signed = doc.finishSignature(new Uint8Array(raw)); // the file, signedThe signature follows the PAdES B-B profile (pyHanko validates it; the EU DSS validator has not been run on it) and is appended after the original bytes, so earlier signatures stay valid. claimedTime is the time your clock gave: Lamina PDF reads no clock. A rect with no area makes an invisible field.
Signing clears the undo history, since a signature can’t be undone, and a file that a certification forbids changing refuses with would-invalidate-signatures. If the signature doesn’t fit the room reserved for it, finishSignature fails with sign-placeholder-too-small: apply the edit again with reserve set to the data.needed it reports. Don’t edit the document between prepareSignature and finishSignature: finishSignature refuses with sign-document-changed.
Certify a file and lock fields
Section titled “Certify a file and lock fields”Two more parameters of the sign edit say what may change after the signature. certify makes it the document’s certification, the author’s signature that a viewer shows as “certified”. "noChanges" allows nothing after it, "formFill" allows filling in form fields and signing, and "annotate" also allows comments. Validators built on pyHanko, 0.38.0 included, refuse a new comment even at that level, so test the file with the validators your readers use. A certification must be the first signature, so the edit fails with sign-certify-not-first on a file that has any.
const edit = { op: "sign", args: { target, params: { claimedTime, certify: "formFill", lock: { action: "include", fields: ["total"] } } } };if (doc.wouldViolate(edit).length === 0) doc.apply([edit]); // a signed file reports "certifyNotFirst"lock locks form fields once the signature is made: "all" of them, the ones fields lists ("include"), or every one but those ("exclude"). A signature field that already holds a /Lock locks the same way without it. A permission (1 to 3) in a lock limits later changes even for a signature that doesn’t certify. A field whose seed values (/SV /MDP) ask for a certification needs certify at that level. Where a lock’s permission is stricter than certify, the stricter level is written.
Afterwards doc.wouldViolate(edit) names the lock or the level an edit would break, and doc.plan().docMdp is the certification’s level (1, 2 or 3). Acrobat Reader’s display of the certification has not been checked. pyHanko reads each level and lock back and accepts or refuses a later change as the standard says.
Stamp the time of the save
Section titled “Stamp the time of the save”Pass metadataDate, the time from your app’s clock, and a save that writes changes records it as the modification date and gives the XMP metadata a new instance ID. instanceId sets that ID yourself. Lamina PDF never reads the clock, so without either option nothing is stamped. On a certified file whose edits are otherwise allowed, the stamp is left out, and the report’s metadataNotUpdated says so.
Extract text and Markdown
You’ll get a PDF’s text out in the form your program needs: plain text to search, Markdown for a language model, JSON with each paragraph’s page and box, or chunks for a search index. Each form writes out the same reading of the document.
In TypeScript, extraction runs in the extract module or the text module. Call init({ extract: true }) once before you open the document, unless your app already loads the text module. In Rust, it needs the crate’s extract feature, which the default features include.
Get the text
Section titled “Get the text”extract with the text format gives the page’s words in the order a person reads them. A blank line separates paragraphs and headings, and tabs separate a table’s cells:
// Read a PDF's text in reading order: paragraphs, headings and table rows, a blank line between// blocks, and nothing a reader can't see.import { Document } from "@laminapdf/sdk";
/** The text of `bytes`, in reading order. Needs `init({ extract: true })`. */export function textOf(bytes: Uint8Array): string { using doc = Document.open(bytes); return doc.extract({ format: "text" });}//! Read a PDF's text in reading order: paragraphs, headings and table rows, a blank line between//! blocks, and nothing a reader can't see.//!//! ```sh//! cargo run -p laminapdf --example extract_text -- <file.pdf>//! ```
use std::error::Error;
use laminapdf::extract::ExtractOptions;use laminapdf::{Document, OpenOptions};
fn main() -> Result<(), Box<dyn Error>> { let input = std::env::args().nth(1).ok_or("usage: extract_text <file.pdf>")?; print!("{}", text_of(std::fs::read(input)?)?); Ok(())}
/// The text of `bytes`, in reading order.pub(crate) fn text_of(bytes: Vec<u8>) -> Result<String, Box<dyn Error>> { let doc = Document::open_bytes(bytes, OpenOptions::new())?; let extraction = doc.extract(&ExtractOptions::new())?; Ok(extraction.to_text().text)}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
A PDF stores where each piece of text is drawn, not the order to read it in. Extraction works the order out, so the text comes back the way the page reads, even when the file drew it in another order:
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.
Get Markdown
Section titled “Get Markdown”Markdown keeps what plain text loses: headings stay headings, lists stay lists, and a table drawn with lines becomes a Markdown table. That structure helps a language model tell a title from a footnote. The pageMarkers option (with_page_markers in Rust) writes a <!-- page N --> comment before each page, so an answer can cite its page:
// 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
The example also writes the JSON and the chunks, which the next sections describe. The Extract text for an LLM recipe shows how to run it on your own files.
Get each block with its box
Section titled “Get each block with its box”The json format returns the whole result as data: every block with its kind, its page and its box (left, top, width and height, in points from the page’s top-left corner). Use it to highlight a passage on the page, to keep a table’s cells apart, or to check what extraction left out. Here each block prints as one line:
// List a PDF's blocks with where they sit: each heading, paragraph, list item and table, its page// and its box in points from the page's top-left corner.import { Document, type ExtractedBlock } from "@laminapdf/sdk";
/** * One line per block: its page number, its kind, its box (left, top, width, height) and its text. * Needs `init({ extract: true })`. */export function blocksOf(bytes: Uint8Array): string { using doc = Document.open(bytes); const extraction = doc.extract({ format: "json" }); return extraction.blocks .map((block) => { const box = block.bbox.map((v) => Math.round(v)).join(" "); const text = block.text.replace(/[\t\n]/g, " "); return `page ${block.page + 1} ${kind(block)} [${box}] ${text}\n`; }) .join("");}
/** The block's kind as the JSON names it, with a heading's level. */function kind(block: ExtractedBlock): string { return block.type === "heading" ? `heading ${block.level}` : block.type.replaceAll("-", " ");}//! List a PDF's blocks with where they sit: each heading, paragraph, list item and table, its page//! and its box in points from the page's top-left corner.//!//! ```sh//! cargo run -p laminapdf --example extract_blocks -- <file.pdf>//! ```
use std::error::Error;use std::fmt::Write as _;
use laminapdf::extract::{Block, BlockKind, ExtractOptions};use laminapdf::{Document, OpenOptions, Pt};
fn main() -> Result<(), Box<dyn Error>> { let input = std::env::args().nth(1).ok_or("usage: extract_blocks <file.pdf>")?; print!("{}", blocks_of(std::fs::read(input)?)?); Ok(())}
/// One line per block: its page number, its kind, its box (left, top, width, height) and its text.pub(crate) fn blocks_of(bytes: Vec<u8>) -> Result<String, Box<dyn Error>> { let doc = Document::open_bytes(bytes, OpenOptions::new())?; let extraction = doc.extract(&ExtractOptions::new())?; let mut out = String::new(); for block in &extraction.blocks { let bbox = block.bbox; let place = [bbox.x0, bbox.y0, bbox.width(), bbox.height()].map(|v| whole_points(v).to_string()); let text = block.text.replace(['\t', '\n'], " "); writeln!( out, "page {} {} [{}] {text}", block.page + 1, kind(block), place.join(" ") )?; } Ok(out)}
/// The block's kind as the JSON names it, with a heading's level.fn kind(block: &Block) -> String { match &block.kind { BlockKind::Heading { level } => format!("heading {level}"), BlockKind::Paragraph => "paragraph".into(), BlockKind::ListItem { .. } => "list item".into(), BlockKind::Caption => "caption".into(), BlockKind::Footnote => "footnote".into(), BlockKind::Table { .. } => "table".into(), // `Other`, and any kind a later version adds. _ => "other".into(), }}
/// `v` in whole points, rounded as the JSON rounds it (to a thousandth), then halves up.fn whole_points(v: Pt) -> f64 { let json = (v.get() * 1000.0).round() / 1000.0; (json + 0.5).floor()}page 1 heading 1 [56 63 116 22] Invoice 42 page 1 paragraph [56 88 237 15] Acme Widgets Ltd · 1 Example Street · London page 1 table [56 148 483 87] 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 page 1 paragraph [468 244 71 15] Total € 135.40
A block is a heading, a paragraph, a list item, a caption, a footnote or a table. A table block also holds its cells, row by row. In Rust, doc.extract returns the same data as Rust types, and doc.extract_json writes the JSON document, laminapdf.extract/1.
Each block also has a confidence from 0 to 1. A block read from the file’s structure tree, the tags that give a tagged PDF its reading order, has 1. A block placed by the layout has 0.75, and 0.5 when its page’s columns could be read in more than one order. With readingOrder: "content-stream", every block has 0.5, since the drawing order may not be the reading order.
Get chunks for retrieval
Section titled “Get chunks for retrieval”A search index or a retrieval pipeline wants pieces of a set size. Chunks are whole paragraphs and tables, grouped up to a token budget, with a new chunk at each heading. Each chunk records the headings above it, the pages and boxes it came from, and where its text sits in the Markdown:
// Split a PDF into chunks for retrieval: whole paragraphs and tables up to a token budget, a new// chunk at each heading, each with the headings above it and the pages it came from.import { Document } from "@laminapdf/sdk";
/** Each chunk of `bytes`: its headings, its pages, its size and its text. Needs `init({ extract: true })`. */export function chunksOf(bytes: Uint8Array): string { using doc = Document.open(bytes); // A small budget, so this short file gives several chunks; 400 to 800 suits most indexes. const chunks = doc.extract({ format: "chunks", chunk: { maxTokens: 60 } }); return chunks .map((chunk) => { const pages = chunk.pages.map((p) => p + 1).join(", "); return ( `${chunk.id} under "${chunk.headingPath.join(" > ")}"\n` + `pages ${pages}, about ${chunk.tokensApprox} tokens\n` + `${chunk.text.trimEnd()}\n\n` ); }) .join("");}//! Split a PDF into chunks for retrieval: whole paragraphs and tables up to a token budget, a new//! chunk at each heading, each with the headings above it and the pages it came from.//!//! ```sh//! cargo run -p laminapdf --example extract_chunks -- <file.pdf>//! ```
use std::error::Error;use std::fmt::Write as _;
use laminapdf::extract::{ChunkOptions, ExtractOptions, MarkdownOptions};use laminapdf::{Document, OpenOptions};
fn main() -> Result<(), Box<dyn Error>> { let input = std::env::args().nth(1).ok_or("usage: extract_chunks <file.pdf>")?; print!("{}", chunks_of(std::fs::read(input)?)?); Ok(())}
/// Each chunk of `bytes`: its headings, its pages, its size and its text.pub(crate) fn chunks_of(bytes: Vec<u8>) -> Result<String, Box<dyn Error>> { let doc = Document::open_bytes(bytes, OpenOptions::new())?; let extraction = doc.extract(&ExtractOptions::new())?; // Chunks are cut from the Markdown, so each one keeps its headings and tables. let markdown = extraction.to_markdown(&MarkdownOptions::new()); // A small budget, so this short file gives several chunks; 400 to 800 suits most indexes. let chunks = extraction.chunks(&markdown, &ChunkOptions::new().with_max_tokens(60)); let mut out = String::new(); for chunk in &chunks { let pages: Vec<String> = chunk.pages.iter().map(|p| (p + 1).to_string()).collect(); writeln!(out, "{} under \"{}\"", chunk.id, chunk.heading_path.join(" > "))?; writeln!(out, "pages {}, about {} tokens", pages.join(", "), chunk.tokens_approx)?; writeln!(out, "{}\n", chunk.text.trim_end())?; } Ok(out)}c0 under "Invoice 42" pages 1, about 58 tokens # 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 | c1 under "Invoice 42" pages 1, about 4 tokens Total € 135.40
A token here is about four characters. That count runs low for code, numbers and scripts other than Latin, so leave room under your model’s limit. overlap repeats whole paragraphs from the end of the previous chunk, and splitOn (with_split_on) chooses where else a chunk starts: at each heading ("headings", the default), at each page ("pages"), or only when the budget runs out ("blocks").
Get the images
Section titled “Get the images”extractImages() (extract_images in Rust) gives the images the pages draw, each as a file you can save:
- JPEG and JPEG 2000 images come out as the file stores them, byte for byte, so nothing is lost to a second compression.
- Every other image is decoded to a PNG, its colours converted to grey or RGB and its mask made transparency.
- An image a page draws twice, or that several pages draw, comes out once, on the first page that draws it.
Each image carries its page, its size, its colour space and its file’s extension. An image Lamina PDF can’t decode is listed in skipped with the reason, and the rest still come out. In TypeScript that includes JBIG2 images (scanned text), which the WebAssembly modules leave out for their size.
Get the links and the outline
Section titled “Get the links and the outline”linksJson() and outlineJson() give every page’s links and the outline (the bookmarks a reader lists in its sidebar) as JSON, in the formats laminapdf.links/1 and laminapdf.outline/1. A link’s page and rectangle are in points from the page’s top-left, and each says where it goes: a page here, a web address or another file. linksCsv() and outlineCsv() give the same as CSV for a spreadsheet, one row a link or an outline item, each item with its level. In Rust they are links_json, outline_json, links_csv and outline_csv on Document.
Find the fields of a flat form
Section titled “Find the fields of a flat form”A form saved flat as a vector PDF has no fields, only boxes, lines and labels. suggestFields(page) (suggest_fields in Rust) reads one page and lists the fields it seems to ask for. Each suggestion has a kind ("text", "date", "checkBox", "radio" or "signature"), a box in points from the page’s top-left, and the label beside it. It also says why it was suggested: a closed box, a ruled line, a run of underscores or a small square. The buttons of one radio group share a group.
A suggestion changes nothing in the document. To accept one, create the field with a createField edit at its box. Areas an existing field covers get no suggestion.
The rules are fixed, so a page always gives the same list. They don’t see round radio buttons, and they can mistake a table of text for fields. A scanned page has no lines or text to read, so it gets no suggestions.
On the third-party forms in Lamina PDF’s test set, about 84% of the real fields are found and 84% of the suggestions are right; on IRS forms alone, about 75%. Those forms were used to tune the rules. On an IRS form they weren’t tuned on, 75% of the fields were found and 73% of the suggestions were right. Expect to reject some.
Reading order
Section titled “Reading order”Extraction reads a two-column page down the left column, then down the right, and puts a title that spans both columns first:
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.
The readingOrder option (with_reading_order in Rust) chooses where the order comes from:
readingOrder |
Where the order comes from |
|---|---|
"auto" (the default) |
The structure tree of a tagged file when it covers the page and looks right, otherwise the layout |
"tagged" |
The structure tree wherever there is one |
"layout" |
The layout alone, columns then rows |
"content-stream" |
The order the page draws its text |
When the layout leaves the order in doubt, such as two columns set very close together, the page raises the extract-column-order-uncertain warning. Troubleshooting text extraction says what to do about it and about the other surprises.
What extraction leaves out
Section titled “What extraction leaves out”Extraction gives you only the text a reader can see. It leaves out:
- invisible text, such as the hidden text layer of a scanned page;
- text off the page, too small to read, or cut away by a clipping path;
- near-white text with nothing behind it, and text painted over by a later shape, image or comment;
- page furniture: running headers and footers, page numbers, and text the file marks as an artifact.
The JSON lists each run it left out under dropped, with the reason and the number of characters, but not the text. To keep the text in that list, set drop: { keepSpans: true }; in Rust, set the options’ drop.keep_spans field to true. To keep page furniture in the blocks, set drop: { furniture: false } (drop.furniture in Rust).
Tables
Section titled “Tables”A table drawn with lines becomes a table block, and Markdown writes it as a table. 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. The JSON keeps one block per page, linked by continues and continuedBy.
A table drawn without lines is only text lined up in columns. To find those too, set tables: "lattice-and-stream" (with_tables(TableMode::LatticeAndStream) in Rust). It finds more tables, and now and then a pair of columns that isn’t one.
Warnings to expect
Section titled “Warnings to expect”Extraction never fails on a page it reads badly. It returns what it could read and adds a warning, which the JSON lists under warnings:
| Warning | What it means |
|---|---|
extract-needs-ocr |
A page has no text to use, such as a scan; send it to OCR (optical character recognition) |
extract-column-order-uncertain |
The page’s columns could be read in more than one order |
extract-struct-tree-ignored |
A tagged page’s structure tree failed the checks, so the layout gave the order |
unmapped-glyph |
A font drew glyphs that map to no character; they come out as � |
extract-table-ambiguous |
A table’s cells merge in a shape a grid can’t hold |
Each page in the JSON also has a textLayer whose status says whether its text is usable:
status |
The page |
|---|---|
native |
Text the file draws |
mixed |
Usable text, though some glyphs map to no character or images cover part of the page |
needs-ocr |
No text to use, such as a scan |
ocr-layer |
A scan with an invisible OCR layer, which extraction leaves out |
empty |
Nothing on it |
Pages that need OCR can go to a layout or OCR model through extractWithModels (ExtractOptions::with_models in Rust); without one, extraction uses its own rules alone.
Next: Troubleshooting text extraction, for empty pages, columns read across and missing characters.
Open and protect password-protected files
You’ll open a PDF that needs a password, and ask your user again when the password is missing or wrong. You need this for bank statements, contracts and other files that people protect before they share them.
This example opens an upload with an optional password and returns the outcome as a value instead of throwing. Its test opens a file encrypted with AES-256 three times: with the right password, with none and with a wrong one:
// 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; }}Pass the password
Section titled “Pass the password”Pass the password when you open the file: Document.open(bytes, { password }). The password goes only to the WebAssembly module. Lamina PDF never saves or logs it, and never puts it in an error.
A PDF can have two passwords. The user password opens the file, and the owner password also lifts its restrictions, such as on printing or copying. Lamina PDF checks your password against both:
- Older files (RC4 and AES-128) check the user password first.
- AES-256 files check the owner password first, as PDF 2.0 requires. So a password that matches both counts as the owner’s.
When the password is missing or wrong
Section titled “When the password is missing or wrong”Opening fails with password-required when you pass no password, and with wrong-password when it matches neither. Nothing else has changed, so ask your user and open the file again.
Passwords with accents and other symbols
Section titled “Passwords with accents and other symbols”A character such as “é” can be written in more than one way in Unicode, so the same password can arrive as different bytes. In TypeScript, Lamina PDF tries the password as you give it and, after wrong-password, again in its NFKC form, the Unicode form that makes such spellings match. Older files also accept a password’s Latin-1 bytes. AES-256 files accept the password as given or in the normalised form that PDF 2.0 asks for (SASLprep).
Save an encrypted file
Section titled “Save an encrypted file”An encrypted file keeps its protection when you save it. An incremental save encrypts what it appends under the key the file opened with, and a full rewrite encrypts every string and stream again. You don’t pass the password a second time. doc.save() draws the random bytes it needs from crypto.getRandomValues, so the call is the same as for any file.
Protect a file with a password
Section titled “Protect a file with a password”doc.setEncryption({ user, owner, permissions }) protects a file when you next save it, with AES-256 (the standard security handler at revision 6). The user password opens the file. The owner password, the permissions password, lifts the limits in permissions: print ("none", "lowResolution" or "highResolution"), copy, fillForms, comment and assemble, each allowed unless you set it to false. Give at least one password, or the edit fails with encryption-no-password.
using doc = Document.open(bytes);doc.setEncryption({ user: "open sesame", owner: "owner secret", permissions: { copy: false } });const protectedBytes = doc.save();With no user password the file opens for anyone and carries only the limits. With no owner password the save makes one and returns it in report.generatedOwnerPassword (use doc.saveWithReport()). Show it once and ask your user to keep it: nothing else can lift the limits.
The save writes the whole file again, so it drops the earlier revisions and breaks any signature. On a signed file it refuses with would-invalidate-signatures until you allow that. A file that claims PDF/A can’t be encrypted, since PDF/A forbids it: the edit fails with encryption-pdfa-conflict, and removeConformanceClaims takes the claim off first.
doc.encryptionInfo() says how a file is protected: the handler, revision, ciphers, key length, what the file permits and which password opened it. It never returns a key.
Remove or change the protection
Section titled “Remove or change the protection”doc.removeEncryption() takes the protection off when you next save. The save is a full rewrite with every string and stream in plain text, no encryption dictionary and none of the file’s earlier revisions, so anyone who gets the file can read it.
Only the file’s owner may lift its protection, and Lamina PDF checks that itself. A file opened with its permissions password may be changed. So may one opened with an open password that allows everything, which is the case when it was protected only to be opened. A file opened with an open password that restricts anything, the empty one included, fails with owner-password-required. Ask your user for the permissions password and pass it to doc.authenticateOwner() first:
using doc = Document.open(bytes, { password: openPassword });doc.authenticateOwner(permissionsPassword); // throws wrong-password if it doesn't matchdoc.removeEncryption();const plainBytes = doc.save();The same check holds when you change the passwords or limits with doc.setEncryption(…) on a file that is already encrypted, and when you save with removeEncryption: true. The password you pass to authenticateOwner is checked against the file and not kept. On a signed file the rewrite breaks the signatures, so the save refuses with would-invalidate-signatures until you allow that.
What stays in memory
Section titled “What stays in memory”Lamina PDF’s engine overwrites the passwords it keeps, but JavaScript can’t overwrite a string. So treat every password your code touches as readable in memory for an unknown time.
The engine, in WebAssembly, keeps the password a document opened with, those of the sources you added or merged into it, and those of a setEncryption waiting for the save. It overwrites these when it drops them, so free a document with using or doc.free() to choose when. doc.authenticateOwner() keeps no password.
Lamina PDF doesn’t overwrite these other copies:
- Your strings. The password you pass, its NFKC form and
report.generatedOwnerPasswordare JavaScript strings, which stay until the garbage collector takes them and aren’t cleared even then. - Messages to a Web Worker. A password you send through the SDK’s client for a Web Worker is copied there, as another string.
- Buffers on the way in and out. Open options and edits such as
setEncryptioncross into WebAssembly as JSON text, and a generated owner password crosses back through buffers too. - The renderers. The rendering packages don’t overwrite their copies, and
@laminapdf/render-hayrokeeps an encrypted file’s password until you close its document. - The viewer.
@laminapdf/viewerkeeps an open file’s passwords as strings in its Web Worker until the document closes.
In Rust, OpenOptions, Secret and MergeInput::password (a Secret) overwrite their buffers when dropped. OpenOptions::with_password, MergeInput::with_password and Secret::from(String) take over a String’s buffer. Any call given a &str copies it. So do Secret::new and SetEncryption::new: pass them a reference and wipe your original, because a String moved into one is dropped unwiped.
To keep the copies few, pass a password straight from its input field to the call, and leave it out of application state, browser storage and logs.
Next: open files you don’t trust.
Open files you don't trust
You’ll open uploads with caps on how much an untrusted file can make Lamina PDF decode, read or draw. You need this on any server or page that opens PDFs from strangers, because a small file can ask for gigabytes of work.
This example opens uploads with tighter limits than the defaults: at most 16 MiB decoded from one stream and 64 MiB in all:
// 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; }}Set only the limits you need
Section titled “Set only the limits you need”That work takes many forms: a stream that inflates to gigabytes, a page tree thousands of levels deep, drawings nested inside drawings. Lamina PDF keeps every file within the limits you pass when you open it. Every limit has a safe default, so you set only the ones you want to change.
Hard and soft limits
Section titled “Hard and soft limits”- Hard limits stop the call with
limit-exceeded. Itsdata.limitnames the limit, so you can tell the user which one. - Soft limits drop the excess with a warning and carry on.
| Limit | Kind | Default | What it caps |
|---|---|---|---|
maxNestingDepth |
hard | 256 | arrays and dictionaries inside each other; saved graphics states (q) |
maxStreamDecoded |
hard | 64 MiB | bytes one stream decodes to, per filter stage |
maxDecodedTotal |
hard | 1 GiB | bytes one call (open, one page’s content, one read) decodes, across all streams |
maxFilterChain |
hard | 8 | filters on one stream |
maxResolveDepth |
hard | 32 | indirect objects in flight while following a chain of references |
maxPageTreeDepth |
hard | 256 | /Kids levels below the page-tree root (a deeper subtree is skipped with a warning) |
maxTreeDepth |
hard | 64 | name and number tree levels, outline depth |
maxStringLength |
hard | 16 MiB | bytes in one string or name |
maxXrefSections |
soft | 4,096 | /Prev hops in the cross-reference table chain (past it, Lamina PDF rebuilds the table by scanning) |
maxObjectNumber |
soft | 8,388,607 | the highest object number kept |
maxWarnings |
soft | 1,000 | warnings kept per document (then one warnings-truncated) |
maxContentOperators |
hard | 10,000,000 | drawing operators run in one content call, counting a form’s each time it is drawn |
maxXobjectDepth |
hard | 32 | forms drawn inside forms |
maxImagePixels |
hard (reserved) | 2²⁸ | pixels of one image |
maxReadWindow |
hard | 256 MiB | one read from a range source (Document.openRange) |
maxScriptLength |
soft | 64 KiB | bytes of one form script Lamina PDF reads; a longer script counts as not handled |
These are the TypeScript names. In Rust they’re builder methods, such as Limits::new().with_max_stream_decoded(…).
Refuse damaged files
Section titled “Refuse damaged files”Lamina PDF repairs damaged files as it opens them and reports each repair as a warning. Pass strict: true to refuse any file that needs repair instead. It then fails with strict.
A file on someone else’s server can also decide how much you download. Open it by ranges and cap the bytes it may fetch with budget.
When a file you trust goes over a limit, Troubleshooting opening and saving files says how to raise it.
Next: keep the page responsive.
Open large files by ranges
You’ll open a PDF on a web server by fetching only the parts you read. A large report opens after a few small requests, and reading its first page fetches that page and little else. You need this when files are too large to download before the first page shows.
This example opens a remote file, then reads its page count and first page:
// Opens a PDF on a web server by range requests: only the parts it reads are downloaded, so a// large file opens without fetching all of it. The server must answer `Range` requests, as most// file hosts and CDNs do; across origins it must also allow the `Range` and `If-Range` headers.// Needs `init()`.import { Document, httpRangeSource } from "@laminapdf/sdk";
/** What a first look at a remote file needs: its page count and the first page's size. */export interface FirstLook { readonly pages: number; /** The first page's displayed size, in points (1/72 inch). */ readonly width: number; readonly height: number;}
/** Opens the PDF at `url` range by range and reads its page count and first page. */export async function firstLook(url: string): Promise<FirstLook> { // The first request reads the end of the file, where a PDF keeps the index of its objects. using doc = await Document.openRange(httpRangeSource(url)); // A read can need bytes that haven't arrived. `ensure` catches the `data-pending` error, fetches // the ranges it names, and runs the read again until it has what it needs. const pages = await doc.ensure(() => doc.pageCount); const first = await doc.ensure(() => doc.pageInfo(0)); return { pages, width: first.width, height: first.height };}Each read fetches the bytes it needs
Section titled “Each read fetches the bytes it needs”Document.openRange fetches only what opening needs: the end of the file, where a PDF keeps the index of its objects, then that index and the document’s catalog. Calls on the document stay synchronous, so a read that needs bytes not fetched yet can’t wait for them. It throws data-pending instead, with the byte ranges it needs. doc.ensure runs your read, fetches those ranges when it throws, and runs it again until it returns:
Document.openRange opens a remote file from the few byte ranges the open needs. A later read, such as doc.pageInfo(0), may need bytes that haven't arrived: it then throws data-pending, naming the ranges it needs. doc.ensure catches the error, fetches those ranges through the source (httpRangeSource), supplies them to the document and runs the read again. Once the bytes are there, the read returns its result.
Wrap every read after the open in doc.ensure, saving included: await doc.ensure(() => doc.save()) fetches whatever the save writes. A read fails with the last data-pending when its fetches bring nothing new, or when it still needs bytes after 1,024 rounds of fetches. Pass maxRounds to Document.openRange to change that number.
The server must answer Range requests
Section titled “The server must answer Range requests”httpRangeSource(url) asks for byte ranges with the Range header, and most file hosts and CDNs answer them. Across origins, the server must also allow the Range and If-Range request headers (Access-Control-Allow-Headers: Range, If-Range) and expose Content-Range, Content-Length and ETag (Access-Control-Expose-Headers). It must not compress the response, or the ranges it sends wouldn’t match the file’s bytes. An error status from the server fails with fetch-failed, its data.status holding the status code.
A server that ignores Range and answers 200 sends the whole file. Lamina PDF then opens that one download, as Document.open would.
A file that changes on the server fails the read
Section titled “A file that changes on the server fails the read”Every request after the first sends If-Range with the ETag the first response gave, when it’s a strong one, or else that response’s Last-Modified date. When the file changes between two reads, the read fails with source-changed rather than mixing two versions. Open the file again to read the new one.
Limit how much a file can make you fetch
Section titled “Limit how much a file can make you fetch”A remote file decides how much you fetch, so cap it when the file comes from someone else. Pass budget to Document.openRange: it’s the most bytes the document may hold, and past it a read fails with source-budget-exceeded. Pass signal with the same options to stop the open’s fetches. Later reads take their own: doc.ensure(read, { signal: AbortSignal.timeout(10_000) }).
The limits for files you don’t trust apply here too: pass limits with the other options.
Check what a file hides
You’ll check a PDF for what its reader can’t see before you publish it, send it or accept it as redacted. A PDF keeps more than its pages show: every earlier revision’s text, who made it, attached files, scripts, and text drawn invisible or under a black box.
This example lists what each file holds, and every redaction that only covered its text:
//! Check what a PDF holds beyond its visible pages before you publish or send it: earlier//! revisions, metadata, attachments, scripts, form values and hidden text, and redactions that//! only covered text instead of removing it.//!//! ```sh//! cargo run -p laminapdf --features extract --example check_what_a_file_hides -- <file.pdf>…//! ```
use std::error::Error;
use laminapdf::reveal::Category;use laminapdf::{CancelToken, Document, OpenOptions};
fn main() -> Result<(), Box<dyn Error>> { let paths: Vec<String> = std::env::args().skip(1).collect(); if paths.is_empty() { return Err("usage: check_what_a_file_hides <file.pdf>…".into()); } for path in &paths { print!("{}", report(path, &what_it_hides(std::fs::read(path)?)?)); } Ok(())}
/// What a file holds beyond its visible pages.#[derive(Debug, PartialEq, Eq)]pub(crate) struct Hidden { /// The kinds of thing it holds, such as `history` or `hidden-content`, in report order. pub(crate) categories: Vec<&'static str>, /// Each place text was hidden rather than removed. pub(crate) redactions: Vec<FailedRedaction>,}
/// A warning that text was hidden rather than removed: a redaction that only covered it, or text an/// earlier revision still holds.#[derive(Debug, PartialEq, Eq)]pub(crate) struct FailedRedaction { /// Its warning code, such as `redaction-not-applied`. pub(crate) code: &'static str, /// The 0-based page it is on, when it is on one. pub(crate) page: Option<u64>,}
/// Opens `bytes` and lists what they hold beyond the visible pages.pub(crate) fn what_it_hides(bytes: Vec<u8>) -> Result<Hidden, laminapdf::Error> { let options = OpenOptions::new(); let doc = Document::open_bytes(bytes, options.clone())?; // `reveal` reads every page and every earlier revision; a server would cancel it on a // deadline through this token. let reveal = doc.reveal(&options, &CancelToken::new())?; Ok(Hidden { categories: reveal.found().into_iter().map(Category::as_str).collect(), // The same warnings `Document::redaction_warnings` gives, read from what `reveal` found. redactions: reveal .redaction_warnings() .iter() .map(|warning| FailedRedaction { code: warning.code(), page: warning.location().page_index, }) .collect(), })}
/// One line for each thing `found` holds, or one saying there is nothing.pub(crate) fn report(path: &str, found: &Hidden) -> String { let mut lines: Vec<String> = found.categories.iter().map(|c| format!("{path}: {c}\n")).collect(); for FailedRedaction { code, page } in &found.redactions { let place = page.map_or_else(String::new, |page| format!(" on page {}", page + 1)); lines.push(format!("{path}: {code}{place}\n")); } if lines.is_empty() { lines.push(format!("{path}: nothing beyond its pages\n")); } lines.concat()}letter.pdf: history letter.pdf: text-in-earlier-revision brochure.pdf: metadata brochure.pdf: hidden-content
The letter’s latest revision deleted a word, but its first revision still holds it, and anyone can read that revision. The brochure has metadata and invisible text on its first page.
What reveal looks for
Section titled “What reveal looks for”Document::reveal reads every object once and sorts what it finds into seven categories. Reveal::found lists the ones the file has:
| Category | What it means |
|---|---|
history |
Earlier revisions, and objects nothing refers to any more |
metadata |
The title, author and dates in the file’s two metadata stores (its document information and its XMP metadata), and metadata on single objects |
attachments |
Embedded files |
active-content |
JavaScript, actions that run on a trigger, and XFA forms |
annotations |
Comments and markup, with their authors |
forms |
Form fields that hold values |
hidden-content |
Hidden text, layers turned off, redaction marks never applied, and annotations that lie wholly off their page |
The Reveal it returns also holds the details: each Info entry, each attachment’s name and size, and each run of hidden text. For each earlier revision, it counts the words that revision holds and the latest one lost, and names the pages they were on.
Forms that use scripts
Section titled “Forms that use scripts”A form’s scripts are hidden from the person filling it in. Lamina PDF never runs them, whether in the library, the reader or the command line. Most form scripts only call Acrobat’s built-in helpers, which format a number as $1,234.50, check a date, or add up a column. Lamina PDF recognises those calls as data and does their work itself, so such forms fill, format and add up as they do in Acrobat. Any other script is skipped: you can still fill the field, but the script doesn’t run.
Document::form_scripts lists every script in a file without returning its text. Each entry says where the script is, how long it is, and whether Lamina PDF handles it: handled for a helper call, not handled for any other script, xfa for a script in an XFA form (Adobe’s older XML form format).
Redactions that didn’t remove the text
Section titled “Redactions that didn’t remove the text”A black rectangle over a name hides it on screen and in print, but the name is still in the file, and copying the text brings it back. Document::redaction_warnings finds three ways a redaction fails:
| Warning | What it found |
|---|---|
covered-text |
Text under an opaque box on the page |
redaction-not-applied |
Redaction marks that were drawn but never applied |
text-in-earlier-revision |
Words an earlier revision holds that the latest doesn’t |
The example reads these warnings from the Reveal with Reveal::redaction_warnings, which gives the same warnings without reading the file again. Document::redaction_warnings would read every page and every earlier revision a second time, so call it only when the warnings are all you need.
Each warning names its page when it has one. Remove the text itself with a tool that deletes what a redaction covers, then save a full rewrite, so no earlier revision keeps it.
Remove what a file hides
Section titled “Remove what a file hides”Once you know what a file holds, you can take it out. Sanitise removes the categories you name, or all of them with Sanitise::all(), and reports each item it removed by the object number reveal lists:
| Category | What goes |
|---|---|
metadata |
The document information, the XMP metadata, metadata on single objects, application data, modification dates and page thumbnails |
attachments |
Embedded files and the comments that hold them |
active-content |
Scripts, actions that run on their own, actions that launch a program, submit a form, import data or open a link outside the file, XFA forms, rich media, named renditions, and references to another file or the web: a reference XObject’s /Ref, a stream’s external data, a movie stored elsewhere, a colour profile an output intent names by reference and an image’s print-shop (OPI) reference |
annotations |
Comments and markup; links, form fields and redaction marks never applied stay |
hidden-content |
Layers that are turned off (their text, images and comments, wherever they are drawn, and the layers themselves), content, comments and links wholly outside the page, and text drawn white on nothing, under 1 point or under something painted over it |
history |
Earlier revisions and objects nothing refers to |
reveal lists plain links (URI to a web address, GoToR to another file) without counting them as active content, since a person follows them only by choosing to; the sanitiser removes them all the same. Other actions whose target is another file or the web, such as an embedded-file jump, a thread or a rendition reading a file from elsewhere, do count.
Form values stay. Hidden content goes without turning a page into a picture: text stays text, and where hidden words sat inside a line, the words after them stay where they were. Some hidden things stay on purpose, and the report lists each in hidden_kept (hiddenKept in TypeScript):
- Invisible text. A scanned page carries the words its OCR found as invisible text, so search and copy work; removing it would break that.
- Text hidden by its clip, form fields wholly outside the page, and redaction marks never applied. Apply the redactions first, then sanitise.
- Hidden text inside a form (a drawing that pages can share) that some place shows. One page may draw white text where it can’t be seen, and another over a dark box, where it can. The text also stays when more than page content can draw the form, such as a comment’s appearance or a pattern.
- Text under an annotation’s appearance, such as a comment’s box or an unapplied redaction, which a reader can move or remove. Text drawn with a blend mode, whose colour on the page can’t be told. Content outside the page whose ink may still reach onto it, and comments a viewer may draw onto the page from beside it: a note’s icon, or markup drawn from points that reach the page.
- Content whose layer Lamina PDF can’t decide, and content it can’t take out, such as a shape that clips what follows. A layer that something kept still names stays turned off.
- Replacement text that the file also uses for content that stays. Screen readers and copy and paste take such text in place of what is drawn. Replacement text that only removed content used goes with it.
A font a page embeds keeps every glyph it was made with, so the shapes of removed characters can stay in the font after a sanitise, though no page draws them.
So reveal can still list hidden content on a sanitised file: the invisible text, and whatever the report says was kept.
To decide what to take, a sanitise reads every page, form, pattern and Type 3 glyph, and the work it does is bounded at 64 million steps. Reading a page costs a step for each content operator it runs, its forms’ included, and for each glyph it shows; reading any of the others costs a step for each operator.
A page with nothing hidden is read once. A page with hidden content is read up to three times as the sanitise takes it out, and once more by the check that follows. So a file of about 20 million operators and glyphs, most of them on pages with hidden content, is about the largest a sanitise takes on; a file with fewer such pages can be larger.
When a form holds hidden text, every page is read again to see where the form is drawn, and once more after a form is edited. Such a file reaches the limit at less than half that size. Past the limit, a sanitise fails with sanitise-limit and changes nothing.
Removing hidden content edits what pages draw. In TypeScript that needs the extract or text module: load one with init({ extract: true }) before you open the file. In the base module a sanitise leaves hidden content out and warns hidden-content-kept, and asking for hidden-content there fails with extract-module-not-loaded.
This example removes every category and prints how many items went from each:
// Remove what a PDF hides before you share it: metadata, attachments, scripts, comments and hidden// content (layers that are off, text no one can see), with a report of every item removed. Hidden// content needs the extract or text module, which `init({ extract: true })` loads. The save rewrites the whole file, so no earlier revision keeps what// was removed.import { Document } from "@laminapdf/sdk";
/** What removing every category took out of `bytes`, as text, and the file as it saves. */export function sanitiseAFile(bytes: Uint8Array): { report: string; clean: Uint8Array<ArrayBuffer> } { using doc = Document.open(bytes); const { sanitised } = doc.sanitise(); if (sanitised === undefined) throw new Error("a sanitise always reports"); const lines = [ `metadata: ${sanitised.metadata.length} removed`, `attachments: ${sanitised.attachments.length} removed`, `active-content: ${sanitised.activeContent.length} removed`, `annotations: ${sanitised.annotations.length} removed`, `hidden-content: ${sanitised.hiddenContent.length} removed`, `history: ${sanitised.history.length} removed`, `hidden content kept: ${sanitised.hiddenKept.length}`, ...sanitised.warnings.map((w) => `warning: ${w.code}`), ]; return { report: `${lines.join("\n")}\n`, clean: doc.save() };}//! Remove what a PDF hides before you share it: metadata, attachments, scripts, comments and//! hidden content (layers that are off, text no one can see), with a report of every item removed. The save rewrites the whole file, so no earlier//! revision keeps what was removed.//!//! ```sh//! cargo run -p laminapdf --example sanitise_a_file -- file.pdf [out-dir]//! ```
use std::error::Error;use std::fmt::Write as _;use std::path::PathBuf;
use laminapdf::{Document, Op, OpenOptions, Sanitise, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: sanitise_a_file file.pdf [out-dir]"; let file = 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 (report, clean) = sanitise(std::fs::read(file)?)?; print!("{report}"); std::fs::write(out.join("sanitise_a_file.pdf"), clean)?; Ok(())}
/// What removing every category took out of `bytes`, as text, and the file as it saves.pub(crate) fn sanitise(bytes: Vec<u8>) -> Result<(String, Vec<u8>), Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let edited = doc.apply(vec![Op::from(Sanitise::all())])?; let report = edited.sanitised.ok_or("a sanitise always reports")?; let mut text = String::new(); for (category, items) in [ ("metadata", &report.metadata), ("attachments", &report.attachments), ("active-content", &report.active_content), ("annotations", &report.annotations), ("hidden-content", &report.hidden_content), ("history", &report.history), ] { writeln!(text, "{category}: {} removed", items.len())?; } writeln!(text, "hidden content kept: {}", report.hidden_kept.len())?; for warning in &report.warnings { writeln!(text, "warning: {}", warning.code())?; } Ok((text, doc.save(&SaveOptions::new())?.bytes))}metadata: 5 removed attachments: 5 removed active-content: 18 removed annotations: 4 removed hidden-content: 8 removed history: 7 removed hidden content kept: 1 warning: field-formatting-removed
The save after it always rewrites the whole file, so a sanitised file is one revision and nothing removed survives in it. If the file is protected, it stays protected. On a signed file the rewrite invalidates every signature, so the save refuses unless you allow that.
Each category also has its own edit: StripMetadata, StripAnnotations, StripAttachments, StripActiveContent and StripHiddenContent. The report’s warnings say what else changed. Form fields can lose their number and date formatting with their scripts, an XFA form may not show as it did, and a PDF/A or PDF/UA claim goes with the metadata. Redaction marks that were never applied stay.
Undo puts back what a sanitise removed. A sanitise that found nothing to remove leaves no step to undo, but the next save still rewrites the file; cancel_rewrite (cancelRewrite() in TypeScript) drops that.
The rewrite keeps the first half of the file’s ID (/ID), which stays the same across saves so signatures and caches can recognise the file. It also links the sanitised file to the original, so anyone holding both can tell they are one document.
Mark what must go
Section titled “Mark what must go”A box drawn over text doesn’t remove it. Real redaction starts with marks: each one is a Redact annotation over text or an area, and it holds only where it is and how the box will look, never the words under it. mark_redaction (markRedaction in TypeScript) marks the lines a selection gives, and mark_redaction_area (markRedactionArea) marks an area. A mark is a comment as far as signatures are concerned, so it saves as an update that approval signatures allow.
Review the marks before anything goes. redaction_marks (redactionMarks()) lists each mark with its review state and the text under it now; SetReviewState (setReviewState) accepts or rejects one. redaction_selection (redactionSelection()) says exactly what a set of marks takes: every glyph a mark touches, the whole word around it, and invisible text within a point of it. It also gives the words to look for elsewhere in the file. A preview draws from it, and applying will remove the same glyphs.
This example marks an area of the first page, accepts the mark and counts what it takes:
// Mark an area of a PDF for redaction, accept the mark, and see what applying it would take.// A mark is an annotation: it holds the area and how the box will look, never the text under it,// and nothing is removed until the marks are applied. The selection says exactly which glyphs go,// whole words with them, so a preview and the removal can't disagree. Needs `init({ extract: true })`.import { Document } from "@laminapdf/sdk";
/** * `bytes` with `area` (`[x0, y0, x1, y1]` of its first page, in points from the top left) marked * and accepted, saved incrementally, and what each mark would take: counts, never the words. */export function markForRedaction( bytes: Uint8Array, area: readonly [number, number, number, number],): { report: string; marked: Uint8Array<ArrayBuffer> } { using doc = Document.open(bytes); const args = doc.markRedactionArea(0, area); const [id] = doc.apply([{ op: "markRedaction", args }]).createdAnnotations; if (id === undefined) throw new Error("a mark is always created"); doc.apply([{ op: "setReviewState", args: { target: id, state: "accepted" } }]); const lines = doc.redactionMarks().map((mark) => { const taken = doc.redactionSelection(mark.page, [mark.mark.area]); const state = mark.review === "accepted" ? "accepted" : "to review"; return `page ${mark.page + 1}: ${state}; glyphs ${taken.glyphs.length}, stretches ${taken.stretches.length}, terms ${taken.terms.length}`; }); // Marks are annotations, so they save as an update the file's signatures allow. return { report: `${lines.join("\n")}\n`, marked: doc.save({ mode: "incremental" }) };}//! Mark an area of a PDF for redaction, accept the mark, and see what applying it would take.//!//! A mark is an annotation: it holds the area and how the box will look, never the text under//! it, and nothing is removed until the marks are applied. The selection says exactly which//! glyphs go, whole words with them, so a preview and the removal can't disagree.//!//! ```sh//! cargo run -p laminapdf --example mark_for_redaction -- file.pdf <x0> <y0> <x1> <y1> [out-dir] # an area of page 1, in points from the top left//! ```
use std::error::Error;use std::fmt::Write as _;use std::path::PathBuf;
use laminapdf::{Document, MarkReview, Op, OpenOptions, RectPt, ReviewState, SaveMode, SaveOptions, SetReviewState};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: mark_for_redaction file.pdf <x0> <y0> <x1> <y1> [out-dir]"; let file = PathBuf::from(args.next().ok_or(usage)?); let mut corner = || -> Result<f64, Box<dyn Error>> { Ok(args.next().ok_or(usage)?.parse()?) }; let (x0, y0, x1, y1) = (corner()?, corner()?, corner()?, corner()?); let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let (report, marked) = mark(std::fs::read(file)?, RectPt::from_points(x0, y0, x1 - x0, y1 - y0))?; print!("{report}"); std::fs::write(out.join("mark_for_redaction.pdf"), marked)?; Ok(())}
/// `bytes` with `area` of its first page marked and accepted, saved incrementally, and what each/// mark would take: counts, never the words themselves.pub(crate) fn mark(bytes: Vec<u8>, area: RectPt) -> Result<(String, Vec<u8>), Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let mark = doc.mark_redaction_area(0, area)?; let id = doc.apply(vec![Op::from(mark)])?.created_annotations.remove(0); doc.apply(vec![Op::from(SetReviewState::new(id, ReviewState::Accepted))])?; let mut report = String::new(); for mark in doc.redaction_marks()? { let taken = doc.redaction_selection(mark.page, std::slice::from_ref(&mark.mark.area))?; let state = if mark.review == MarkReview::Accepted { "accepted" } else { "to review" }; writeln!( report, "page {}: {state}; glyphs {}, stretches {}, terms {}", mark.page + 1, taken.glyphs.len(), taken.stretches.len(), taken.terms.len() )?; } // Marks are annotations, so they save as an update the file's signatures allow. let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok((report, doc.save(&options)?.bytes))}page 1: accepted; glyphs 19, stretches 1, terms 4
Marking removes nothing yet: applying the marks comes in a later release.
From TypeScript and the command line
Section titled “From TypeScript and the command line”@laminapdf/sdk doesn’t have reveal or the redaction warnings yet, though it can sanitise. The command line runs the same checks: laminapdf reveal reports each category, and laminapdf check reports failed redactions with its other warnings. Inspect and check PDFs shows both.
Next: open files you don’t trust, with limits on the work an uploaded file can make Lamina PDF do.
Attachments
You’ll work with the files a PDF carries: a spreadsheet behind a chart, an e-invoice’s XML, a contract’s earlier draft. You need this to give people those files, or to attach files to a document your app makes or edits.
Make an invoice Factur-X shows every step in Rust and TypeScript. This page explains the parts.
List the files
Section titled “List the files”attachments() lists every file the document carries, each once. A file says what holds it (holders):
- the document’s list of attachments, which every viewer shows;
- the document, a page or an annotation it is associated with, for example the data a chart on page 3 was made from;
- a paperclip annotation on a page.
Each file gives its name, description, MIME type, size and dates as the PDF states them, and its relationship to what it belongs to: source, data, alternative, supplement or another.
Save a file out
Section titled “Save a file out”attachmentBytes(id) gives a file’s bytes exactly as attached, and compares them with the MD5 checksum the PDF records: matches, mismatch or absent. A mismatch means the bytes changed after the checksum was written, so say so before anyone trusts the file.
Lamina PDF never opens an attached file. Saving one is your app’s job, and a program, such as an .exe or a script, deserves a warning first.
The document’s limits apply: a file larger than maxStreamDecoded is refused with limit-exceeded before it is read.
Attach, describe and delete
Section titled “Attach, describe and delete”Each of these is one edit, which undo takes back:
attachFile(name, bytes, mime, options)attaches a file. A file larger thanattachmentLimit(), the document’smaxStreamDecoded, is refused withattachment-too-large: it could never be saved out again.options.attachToassociates it with the document, a page or an annotation, andoptions.relationshipsays how. The dates come from your app’s clock, never from Lamina PDF’s.updateAttachment(id, patch)changes a file’s name, description, MIME type or relationship. Its bytes stay as they are.deleteAttachment(id)takes a file out of the list and every association. A paperclip annotation that holds the same file keeps it, and the edit warnsattachment-still-held.
An incremental save keeps a deleted file in the PDF’s earlier revisions; save with mode: "fullRewrite" to drop it.
PDF/A and signed files
Section titled “PDF/A and signed files”- PDF/A-1 and PDF/A-2 allow no attached files but PDF/A ones, so attaching warns
pdfa-attachment-forbiddeninplan(). - PDF/A-3 allows any file that has an association, a MIME type and a modification date; one without warns
pdfa-attachment-incomplete. Attaching never raises the file’s PDF version. - A certified file allows no attachment edits at any certification level. A file with approval signatures only takes them in an update after the signatures.
- A file with usage rights takes each edit only when its rights grant it: attaching needs the right to create files, changing one the right to modify, deleting one the right to delete. Attaching to a page is never covered, and attaching to an annotation also needs the right to modify annotations.
wouldViolate(op)says so before the edit.
Read a portfolio
Section titled “Read a portfolio”A portfolio is a PDF that presents its attached files as the main content, with columns such as an owner or a due date. collection() reads its columns, how its files are sorted, the view it asks for and each file’s values; it is undefined for any other PDF.
Next: Save a PDF, for what a signed or repaired file allows.
Inspect a PDF
You’ll look inside a PDF: its version, the standards it claims, its fonts and colour profiles, and the objects it is made of. You need this to debug a file another tool wrote, to check a font is embedded before printing, or to build a developer view.
Nothing here changes the document, and nothing is verified: a claim is what the file says. In TypeScript these reads need the extract or text module (loadExtract()), as properties() does.
Version and claims
Section titled “Version and claims”conformance() gives the %PDF-x.y header’s version, the catalog’s /Version, and the claims the file makes: PDF/A (part and level, from its XMP metadata), PDF/UA (part) and PDF/X (GTS_PDFXVersion, from the XMP metadata or the Info dictionary). A claim says the file was written to meet a standard; veraPDF tells you whether it does.
Fonts and colour profiles
Section titled “Fonts and colour profiles”fonts(pages) lists the fonts the pages use, once each: the pages’ own, those of the forms and patterns they draw, and those of their annotations’ appearances, as pdffonts lists them. properties() lists only the fonts the page content uses, without coverage. Each font says its type, whether the file embeds it or only a subset of it, its encoding, its object, and whether a ToUnicode map turns its codes into text. toUnicodeCoverage counts how many of the font’s codes that map covers: a font with codes the map leaves out gives text that can’t be searched or copied.
colorProfiles() lists the output intents (what a PDF/A or PDF/X file is meant to print or show on) and every ICC profile the file carries, each with what its header says: its colour space, device class, version and description.
Objects, streams and references
Section titled “Objects, streams and references”objectCount()counts the objects without reading any, andobjectEntry(num)reads one object’s entry.objects()lists every object by number, with its kind, its/Typeand/Subtype, and where it is stored: at an offset in the file, inside an object stream, or made in this session.trailer()is the root of it all:/Root,/Info,/ID.object(num)gives one object’s value as plain data (dictionaries, arrays, names, strings, references), a stream’s filters and stored length, and the revision that last wrote it.objectSyntax(num)writes it as PDF syntax, to copy.streamBytes(num, view, max)reads the firstmaxbytes of a stream,"raw"as stored or"decoded". A decoded stream is decoded only that far, and one byte more to know whether there is more:totalis absent for a longer one. Decoding never goes past the document’s limits: withmaxpastmaxStreamDecoded, a stream that inflates further is refused withlimit-exceeded, and its raw bytes can still be read.referencesTo(num)lists the places that refer to an object, with the key path inside each (/Kids[2]). The first call reads every object to index them, so a large file takes a moment; later calls reuse the index until the document changes.revisionCount()counts the revisions;revisions()lists each revision an incremental update added, with the objects it added, changed and freed, and whether a signature covers exactly that revision.
These reads are the same in Rust (Document::conformance, fonts, color_profiles, objects, object, stream_bytes, references_to, object_syntax, revisions) and in TypeScript, where names are camelCase.
In the reader
Section titled “In the reader”The web reader shows all of this in its object inspector: More › Inspect objects, Document properties › Inspect…, or the commands Inspect objects and Go to object… in the command palette. It replaces the pages until Back to pages, with tabs for Objects, Revisions, Fonts, Colour and Conformance. It isn’t offered on a phone-sized screen.
Next: Check what a file hides, for a file’s earlier revisions and hidden content.