Skip to content
Lamina PDF
0.9.0
GitHub
Open the web app

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.

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:

packages/sdk/examples/extract-text.ts
// 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" });
}

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:

Text runsfrom every pageLinesruns joinedBlocksparagraphs, tablesReading ordertags, else columnsSet asideinto droppedinvisible · off-page · tiny · clippedlow-contrast · covered · artifactrunning-header · running-footerpage-numberMarkdownJSONlaminapdf.extract/1ChunksText runsfrom every pageSet asideinto droppedinvisibleoff-pagetinyclippedlow-contrastcoveredartifactrunning-headerrunning-footerpage-numberLinesruns joinedBlocksparagraphs, tablesReading ordertags, else columnsMarkdownJSONlaminapdf.extract/1Chunks
Extraction joins a page's text runs into lines and blocks, orders them, then writes Markdown, JSON and chunks.

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:

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

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.

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:

packages/sdk/examples/extract-blocks.ts
// 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("-", " ");
}

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.

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:

packages/sdk/examples/extract-chunks.ts
// 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("");
}

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").

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.

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.

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.

Extraction reads a two-column page down the left column, then down the right, and puts a title that spans both columns first:

12345671: the title, across both columns2–4: down the left column5–7: then down the right column12345671: the title, across both columns2–4: down the left column5–7: then down the right column
On a two-column page, a title across both columns comes first, then the left column, then the right.

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.

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

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.

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.