# Document tools

> Watermarks, headers and footers, Bates numbering, attachments, bookmark editing, document properties, page labels, images to PDF and an archive readiness check, in the viewer and in the headless API.

Document tools change the document itself rather than adding annotations on top of it. All of them are methods of the headless `PdfDocument`; the viewer offers most of them in its menu and sidebar.

```ts
import { readFile, writeFile } from 'node:fs/promises';
import { openPdfDocument } from '@birchui/pdf/engine';

const pdf = openPdfDocument(await readFile('production/NWT-services-agreement.pdf'));

pdf.addWatermark({ text: 'CONFIDENTIAL', rotation: 45, opacity: 0.2, color: '#cf222e' });
pdf.addHeaderFooter({
  header: { right: '{date}' },
  footer: { left: 'Northwind Analytics Ltd', center: 'Page {page} of {pages}' },
  fontSize: 9,
  date: '12 March 2026',
});
pdf.addBatesNumbers({ prefix: 'NWT-', start: 1201, digits: 6 });
pdf.setMetadata({ title: 'Services Agreement', author: 'Northwind Analytics Ltd', keywords: 'contract, Fabrikam' });

await writeFile('production/NWT-001201.pdf', (await pdf.save()).bytes);
```

In the headless API every tool is one step in the undo history, emits `documentChange` with a `reason`, and is saved as part of an incremental update when nothing else forces a rewrite.

## In the viewer

| Where | Tool |
| --- | --- |
| Menu, under **Document tools** | Watermark, Header and footer, Bates numbering, Crop pages, Flatten annotations, Flatten form, Optimize and save |
| Menu | Document properties, Security, Compare documents, Sign document |
| Bookmarks panel | Add, rename and delete bookmarks |
| Attachments panel | Attach (also by dropping files on the panel), open, save and remove files; a portfolio is shown as a table |
| Pages panel | Crop and split, next to the [page tools](https://docs.birchui.com/pdf/page-tools.md) |

Every tool is one step in the viewer's undo history, like an annotation edit. Ctrl+Z after a watermark removes the watermark from the page and leaves everything done before it undoable; Ctrl+Y puts it back. The document stays open: the scroll position, zoom, selection and sidebar do not change, and `documentLoad` does not fire.

To show the new page content, the viewer writes a preview of the open document after each tool (and after undoing or redoing one) and hands it to the renderer. The preview is never saved; `save()` writes the document itself. `documentChange` fires when the viewer has switched to the new content; the visible pages repaint right after, without going blank in between.

The dialogs cover the common cases: the watermark dialog sets the text, size, angle, opacity and colour of a centred watermark on every page; the header and footer dialog has the six slots and a font size; the Bates dialog has prefix, start, digits, suffix and position. For page ranges, underlays and the other options, call the methods:

```ts
viewer.on('documentChange', ({ reason }) => console.info(`page content replaced after ${reason}`));

await viewer.addWatermark({ text: 'CONFIDENTIAL', opacity: 0.2, pages: [0, 1] });
await viewer.addHeaderFooter({ footer: { center: 'Northwind Analytics · page {page} of {pages}' } });
await viewer.addBatesNumbers({ prefix: 'NWT-', digits: 6, start: 1201 });
await viewer.cropPages([0], [36, 36, 576, 756]);
await viewer.cropPages([1], [36, 300, 576, 756], { removeContent: true });
await viewer.flatten('annotations');
await viewer.setOutline([...viewer.getOutline(), { title: 'Signature page', pageIndex: 2 }]);
await viewer.setMetadata({ title: 'Master Services Agreement, signed copy' });
await viewer.setPageLabels([{ startPage: 0, style: 'roman-lower' }]);

viewer.undo();
```

A plain crop only sets the crop box: the content outside it stays in the file and comes back when the crop is removed, and text extraction still finds it. With `removeContent: true`, or **Remove the cropped content from the file** ticked in the crop dialog, the text, images, vector paths and shadings that lie wholly outside the box are deleted from the page content, form XObjects that reach outside are rewritten the same way, and the media box and the other boxes are set to the crop box. What touches the box is kept whole: a glyph, an image or a path that straddles the edge stays in the file, clipped by the box. Annotations and form fields outside the box are not removed; delete or flatten them first. The step can be undone until the document is saved and closed.

| Viewer method | Returns |
| --- | --- |
| `addWatermark(options)`, `addHeaderFooter(options)`, `addBatesNumbers(options?)`, `cropPages(indices, box \| null, options?)`, `flatten(mode?)` | A promise that resolves when the viewer has switched to the new page content |
| `getOutline()`, `setOutline(items)` | The bookmarks; a promise |
| `getMetadata()`, `setMetadata(patch)` | The document properties; a promise |
| `getAttachments()`, `addAttachment(input)`, `removeAttachment(name)` | The attachments; a promise, and a promise of `true` when a file was removed |
| `getPageLabels()`, `setPageLabels(ranges)` | One label per page; a promise |

The options are the same as in the headless API below. The promises reject with the error of the tool, for example a `PdfPermissionError` on a protected file. `flatten()` takes `'annotations'`, `'forms'` or `'all'` (the default) and is undoable too: undo brings the annotations and fields back as editable objects.

## Compress and optimize

**Tools → Compress and optimize…** (`optimize`) offers three presets and shows the size of the file as it would be saved now next to the size of the optimised copy, with the saving in percent, before anything is downloaded.

| Preset | What it does |
| --- | --- |
| Lossless | Rewrites the file, drops unused objects, merges duplicate streams and recompresses; pages look exactly the same |
| Balanced | Lossless, plus images above 150 dpi are downsampled and embedded fonts are subset |
| Smallest | As Balanced with images at 96 dpi and lower JPEG quality |

`viewer.optimizeCopy(preset)` returns `{ bytes, before, after }` without touching the open document. Protected documents are compressed without image or font changes, and a digitally signed document is refused because a rewrite would break its signatures.

## Export pages and text

**Tools → Export pages as images…** (`exportImages`) renders a page range as PNG or JPEG at 72 to 300 dpi, with the annotations, and saves either one ZIP archive or one file per page. **Tools → Export text…** (`exportText`) saves the text of a page range as a UTF-8 file, with a line that marks where each page starts if you want one. Both need the copy permission.

```ts no-check
const files = await viewer.exportPageImages({ pages: [0, 1], format: 'jpeg', dpi: 150, quality: 0.8 });
const text = viewer.exportText({ pages: [0], pageBreaks: false });
```

## Sanitize

**Protect → Sanitize document…** (`sanitize`) removes hidden information before a file is shared. The dialog counts what it found for each kind, removes the kinds you leave ticked, lists what was removed and saves that list as a text report.

| Kind | Removed |
| --- | --- |
| Metadata and document properties | The information dictionary, XMP packets, private application data |
| Hidden layers | Layers that are switched off, with the page content that belongs to them |
| Attachments | Embedded files, file attachment annotations, portfolio settings |
| Scripts and automatic actions | JavaScript, open actions, additional actions, the calculation order |
| Comments and annotations | Every annotation except links and form fields |

The cleaned document is written as a full rewrite and loaded in place of the open one. The step cannot be undone. Signed documents are refused and protected ones need their protection removed first.

### What is removed

- **Earlier revisions.** A PDF that was saved incrementally still holds every earlier version of its changed objects. The full rewrite writes only the objects the cleaned document uses, so text that was edited away, deleted annotations and replaced form values of earlier saves are gone, whichever kinds are ticked.
- **Metadata.** The information dictionary (title, author, subject, keywords, producer, dates), every XMP packet (`/Metadata` on the catalog, on pages, images and any other object), `/PieceInfo` private application data and `/LastModified`. The file identifier is renewed.
- **Hidden layers.** A layer counts as hidden when the default configuration switches it off. Its marked content is cut out of the page content streams, out of form XObjects at any nesting depth and out of annotation appearance streams; form XObjects, images and annotations that belong to the layer are removed whole; the layer disappears from the layer list. Visible layers are kept.
- **Attachments.** The embedded files name tree, file attachment annotations with their files, associated files and the portfolio (collection) settings.
- **Scripts and automatic actions.** Document-level JavaScript, the open action when it is an action and not a plain destination, every additional-actions dictionary (`/AA`) on the catalog, pages, fields and annotations, JavaScript actions on links, buttons and bookmarks, and the calculation order of the form.
- **Comments.** Every annotation except links and form field widgets, with its popup, reply chain and appearance stream.

### What is not removed

- **Visible page content**, including text that is covered by a shape, white on white, outside the crop box or too small to read. Use [redaction](https://docs.birchui.com/pdf/redaction.md) for content that has to go.
- **Form field values.** A filled form keeps its values and its fields; flatten or reset the form first if they must not travel.
- **Links** and their targets, bookmarks, named destinations, page labels and the tag structure, which may contain alternative text.
- **Hidden layer content inside tiling patterns and Type 3 font glyphs.** These are not searched for layer marks.
- **Layers switched off only by a viewer preference or an alternative configuration.** Only the default configuration decides what is hidden.
- **Data inside images**: EXIF and other tags within a JPEG or JPEG 2000 stream, and pixels outside an image's clip.
- **Embedded fonts**, whose name tables can carry a foundry or licensee name.

The tests plant a marker string in each removable place of one file (information dictionary, XMP, private data, an attachment and its name, four kinds of script, a comment and its appearance, an earlier revision, and a hidden layer on the page, in a form XObject, in a nested form XObject and in a field appearance) and check that `pdftotext`, `qpdf --json`, the expanded file from `qpdf --qdf` and a search of every decoded object find none of them afterwards, while the visible text, the visible layer and the field value are still there.

```ts no-check
import { sanitizePdf } from '@birchui/pdf/engine';

const { bytes, report } = await sanitizePdf(source, { comments: false });
console.info(report.metadata, report.hiddenLayers, report.attachments, report.scripts);
```

## Watermarks

`addWatermark(options)` draws text on the pages.

| Option | Default | Meaning |
| --- | --- | --- |
| `text` | | The text; required |
| `pages` | all | Zero-based page indexes |
| `position` | `'center'` | `'center'`, `'top-left'`, `'top-center'`, `'top-right'`, `'center-left'`, `'center-right'`, `'bottom-left'`, `'bottom-center'`, `'bottom-right'`, or `{ x, y }` in points |
| `fontSize` | `48` | Points |
| `rotation` | `0` | Degrees, counter-clockwise |
| `color`, `opacity` | | A hex colour, and 0 to 1 |
| `font` | `'Helvetica'` | `'Helvetica'`, `'Helvetica-Bold'`, `'Times-Roman'`, `'Times-Italic'` or `'Courier'` |
| `layer` | `'over'` | `'under'` draws beneath the page content |
| `margin` | `36` | Distance from the page edge for the edge positions |
| `fonts` | the document's fonts | A font registry for text outside Western European; see [Fonts](https://docs.birchui.com/pdf/fonts.md) |

Positions follow the page as it is displayed, so a stamp is upright on a rotated page. A watermark is ordinary page content: it cannot be selected in the viewer, and it is not a security feature, because anyone with a PDF editor can remove it.

## Headers and footers

`addHeaderFooter(options)` takes `header` and `footer`, each with `left`, `center` and `right` texts. The texts may contain `{page}`, `{pages}`, `{date}` and `{fileName}`.

| Option | Default | Meaning |
| --- | --- | --- |
| `pages` | all | Pages to stamp. `{page}` is the real position of the page in the document. |
| `startNumber` | `1` | Number of the first page |
| `totalPages` | the page count | Value of `{pages}` |
| `date` | today, as `YYYY-MM-DD` | A `Date`, or a string that is used as it is |
| `fileName` | `''` | Value of `{fileName}` |
| `margin` | `36` | A number, or `{ top, bottom, left, right }` |
| `fontSize`, `color`, `font`, `fonts` | `10`, black, Helvetica | As for watermarks |

## Bates numbering

`addBatesNumbers(options)` stamps a sequential number on each page: `prefix`, a zero-padded number with `digits` places (default 6) that starts at `start` (default 1), and `suffix`, at `position` (default `'bottom-right'`). With `pages`, the selected pages are numbered consecutively.

`formatBatesNumber(index, options)` returns the label of the page at `index` without touching a file, for building an index of a production:

```ts
import { formatBatesNumber } from '@birchui/pdf';

const options = { prefix: 'NWT-', start: 1201, digits: 6 };
const first = formatBatesNumber(0, options);
const last = formatBatesNumber(pdf.pageCount - 1, options);
```

## Attachments

```ts
pdf.addAttachment({
  name: 'schedule-a-fees.csv',
  data: new TextEncoder().encode('service,monthly fee\nAnalytics,1820.00\n'),
  mimeType: 'text/csv',
  description: 'Fee schedule',
});

for (const file of pdf.getAttachments()) console.info(file.name, file.size, file.source);
pdf.removeAttachment('schedule-a-fees.csv');
```

`getAttachments()` returns the embedded files of the document (`source: 'document'`) and the files of file-attachment annotations (`source: 'annotation'`, with a `pageIndex`), each with its `data`. Adding a file under an existing name replaces it. `removeAttachment` removes a document-level file and returns whether one was found.

The media type is taken from the file extension when `mimeType` is left out. Relationships (`relationship`, for PDF/A-3 style associated files), checksums, Unicode file names, portfolios, the `attachmentOpen` event and drag-and-drop in the viewer are described under [Attachments and portfolios](https://docs.birchui.com/pdf/attachments.md).

## Bookmarks

`getOutline()` returns the bookmark tree and `setOutline(items)` replaces it. An item has a `title`, a target (`pageIndex` with optional `left`, `top` and `zoom`, or a `uri`), optional `isOpen`, `color`, `isBold` and `isItalic`, and `children`.

```ts
const outline = pdf.getOutline();
pdf.setOutline([
  ...outline,
  {
    title: 'Schedule A: Fees',
    pageIndex: 12,
    isBold: true,
    children: [{ title: 'Payment terms', pageIndex: 13, top: 640 }],
  },
]);
```

Bookmarks follow their pages when pages are moved. An empty array removes the outline. In the viewer, the Bookmarks panel adds a bookmark for the current page, and renames or deletes the focused one.

## Document properties

`getMetadata()` returns `title`, `author`, `subject`, `keywords`, `creator`, `producer`, `created`, `modified`, `trapped`, a `custom` record of other entries and the raw `xmp` packet. `setMetadata(patch)` changes the fields you pass; `null` removes a field. Both the information dictionary and the XMP packet are written, and the modification date is updated.

The **Document properties** dialog shows them with the page count, page size, file size, PDF version and encryption, and edits title, author, subject and keywords.

The same dialog has an **Initial view** section for what a reader does when it opens the file: the panel to show (bookmarks, thumbnails, attachments, layers, full screen), the page layout, the page to open at, the zoom (fit page, fit width or a percentage) and whether the window title shows the document title. In code these are `getInitialView()` and `setInitialView({ pageMode, pageLayout, openPage, zoom, displayDocTitle })` on the viewer and on a document session; they write `PageMode`, `PageLayout`, `OpenAction` and `ViewerPreferences`. The change is one undo step.

## Page labels

Page labels are the page "numbers" a reader shows, such as `i`, `ii`, `1`, `2`, `A-1`. `getPageLabels()` returns one label per page and `setPageLabels(ranges)` defines them:

```ts
pdf.setPageLabels([
  { startPage: 0, style: 'roman-lower' },
  { startPage: 4, style: 'decimal' },
  { startPage: 40, style: 'decimal', prefix: 'A-', start: 1 },
]);
```

`style` is `decimal`, `roman-upper`, `roman-lower`, `alpha-upper`, `alpha-lower` or `none` (prefix only). The viewer shows labels in the page box and under the thumbnails, and accepts them in the page box. It has no dialog to edit them.

## Images to PDF

`imagesToPdf(images, options)` builds a document with one page per image. PNG, JPEG, GIF, BMP and TIFF files are read by the package; WebP, SVG and anything else go through the `decodeImage` callback (see [Image formats](https://docs.birchui.com/pdf/content-editing.md#image-formats)):

```ts
import { imagesToPdf } from '@birchui/pdf/engine';

const receipts = await imagesToPdf([frontScan, { data: backScan, dpi: 300 }], {
  pageSize: 'a4',
  margin: 24,
  fit: 'contain',
  metadata: { title: 'Expense receipts March 2026', author: 'Mei Chen' },
});
```

| Option | Default | Meaning |
| --- | --- | --- |
| `pageSize` | `'image'` | `'image'` sizes each page to its image, `'a4'`, `'letter'`, or `{ width, height }` in points |
| `dpi` | `72` | Resolution used to size an image; can also be set per image |
| `margin` | `0` | Points around the image |
| `fit` | `'contain'` | `'contain'`, `'cover'` or `'none'`, for fixed page sizes |
| `metadata` | | `title`, `author`, `subject`, `keywords`, `creator` |
| `decodeImage` | | `(bytes, mimeType) => { width, height, data }` with RGBA pixels, for formats the package does not read |

JPEG data is embedded as it is; every other format is decoded and stored losslessly, with transparency as a soft mask. A file that is not an image rejects with an `ImageFormatError`, and a WebP or SVG without `decodeImage` with an `ImageDecoderRequiredError`.

In the viewer, **Create PDF from images…** on the Tools tab asks for one or more image files, then for the page size and margin, builds the document and opens it: in a new tab when [document tabs](https://docs.birchui.com/pdf/customization.md#document-tabs) are on, otherwise in place of the open document, after a confirmation when that has unsaved changes. The command is available without a document. It is the `imagesToPdf` command.

## Archive readiness check

`checkArchiveReadiness(bytes)` inspects a file for the most common reasons PDF/A validation fails:

```ts
import { checkArchiveReadiness } from '@birchui/pdf/engine';

const report = checkArchiveReadiness(finalContractBytes);
if (!report.isLikelyConformant) {
  for (const finding of report.findings) console.warn(finding.severity, finding.rule, finding.message);
}
console.info(report.declared, report.fonts.filter((font) => !font.isEmbedded));
```

It reports on encryption, fonts that are not embedded, missing or undeclared XMP metadata, a missing output intent, JavaScript and Launch actions, embedded files, transparency, LZW compression and a missing file identifier, graded by the PDF/A part the file declares.

> **Warning**
>
> This is a quick pre-flight check. `validatePdfA`, described below, checks the rules of PDF/A-2b in more depth; a full validator such as veraPDF checks several hundred more.

## Conversion to PDF/A-2b

`convertToPdfA(bytes, options?)` rewrites a file for PDF/A-2b and validates the result with the rules the package implements:

```ts
import { convertToPdfA } from '@birchui/pdf/engine';

declare const finalContractBytes: Uint8Array;
declare const liberationSans: Uint8Array;
declare const liberationSansBold: Uint8Array;

const result = await convertToPdfA(finalContractBytes, {
  fonts: { Helvetica: liberationSans, 'Helvetica-Bold': liberationSansBold },
});
for (const violation of result.validation.violations) {
  console.warn(violation.clause, violation.rule, violation.message);
}
console.info(result.isConformant, result.removed, result.fonts, result.bytes.length);
```

- **Added:** an output intent with an sRGB profile that the package generates (`buildSrgbProfile()`, an ICC version 2 display profile of about 2.7 KB), an XMP packet that mirrors the document information and declares part 2, conformance B, a file identifier, and an appearance stream for every annotation that had none (a blank one for form fields without a value).
- **Removed:** document and page actions, JavaScript, the scripts of form fields and annotations, Launch and the other actions PDF/A forbids, XFA data and the `NeedAppearances` flag, rollover and down appearances, image interpolation, and embedded files (`keepAttachments: true` keeps them; PDF/A-2 allows only attachments that are themselves PDF/A). `removed` names what was taken out.
- **Changed:** every annotation is made printable and visible, as the standard requires.
- **Fonts:** every simple font that is not embedded, which includes the standard 14 fonts, is replaced by a subset of the TrueType font you supply under its name in `fonts`. The keys are the standard names (`Helvetica`, `Helvetica-Bold`, `Times-Roman`, `Courier`, `ZapfDingbats` and so on; `Arial` and `TimesNewRoman` are read as their standard equivalents) or the exact font name. The character codes in the page content are not changed, so the replacement must be metric-compatible: `result.fonts` lists each replaced font with the number of characters whose width differs by more than two thousandths of an em. Liberation Sans, Serif and Mono match Helvetica, Times and Courier in their regular faces. Text boxes and form values in other scripts are embedded through the `fonts` option of the document, as described under [Fonts](https://docs.birchui.com/pdf/fonts.md).
- **Refused:** when a font is not embedded and no replacement was supplied, the conversion throws a `PdfWriteError` that names the font and the key to supply. A replacement with CFF outlines, or one without glyphs for the characters of the font, is refused the same way, as is a composite font that is not embedded. Encrypted and signed files are refused too.
- **Not done:** transparency, colour spaces and image compression are not rewritten. Content in DeviceCMYK, which the sRGB output intent does not cover, is reported as a violation rather than converted.

### What the validator checks

`validatePdfA(bytes)` runs the same checks on any file and returns `{ isValid, violations, rulesChecked }`, each violation with the clause of ISO 19005-2 it belongs to:

| Rule | What is checked |
| --- | --- |
| `header`, `file-id`, `encryption` | `%PDF-1.n` header with a binary comment, a file identifier, no encryption |
| `stream` | no LZW or Crypt filter and no external stream data |
| `output-intent` | a `GTS_PDFA1` output intent with one well-formed ICC profile whose component count matches |
| `device-colour` | DeviceRGB, DeviceCMYK and DeviceGray in page content, forms, patterns, shadings, images, inline images and appearance streams are covered by the output intent or a default colour space |
| `transparency` | no transfer functions or halftone phase, blend modes of PDF 1.7 only, a blending colour space when there is no output intent |
| `image`, `xobject` | no interpolation, alternates or OPI; no PostScript or reference XObjects |
| `fonts` | every font used is embedded; `CIDFontType2` has a `CIDToGIDMap`; TrueType encodings follow 6.2.11.6; a missing `ToUnicode` map is a warning, since level B does not need it |
| `annotations` | no 3D, sound, screen or movie annotations; printable and visible; a normal appearance stream and no other appearance |
| `actions` | no JavaScript, Launch or other forbidden action, only the four allowed named actions, no additional actions on the catalog, pages, annotations or fields |
| `metadata` | an XMP packet that declares part 2 and a conformance level, and agrees with the document information for title, author, subject, keywords, creator, producer and both dates |
| `forms`, `embedded-files` | no XFA, `NeedAppearances` or `Requirements`; embedded files are reported as a warning because their own conformance is not checked |

> **Warning**
>
> `isConformant` and `isValid` are the verdict of this validator, of `checkArchiveReadiness` and, in the tests, of `qpdf --check`, `pdffonts` (every font embedded) and poppler. The output is also checked with veraPDF 1.28 (profile PDF/A-2b) in the validation run, when veraPDF is installed or `BIRCHUI_VERAPDF_JAR` points at its application jar: of the 44 fixture files 38 convert (the others are encrypted or have fonts that cannot be replaced), and the files made by office software, the scans and the sample all pass. The files that veraPDF rejects fail only on the rules listed below as reported and not repaired, and `isConformant` is `false` for each of them. The conversion repairs: missing output intent and metadata, forbidden actions, scripts and attachments, hidden annotations, missing annotation appearances, button widgets whose appearance is not a state dictionary, transfer functions and halftone phase in graphics states, LZW compression, image interpolation, the `AS` entry of layer configurations, a missing `CIDToGIDMap`, and stream syntax (every object is serialised anew). It reports and does not repair: DeviceCMYK and spot colour content without a matching output intent, the interpolation flag of inline images, content streams with operators that are not part of PDF or with names of resources that do not exist, and annotations of kinds the engine does not model that have no appearance. The rules above are the central ones of PDF/A-2b, not all of them: the content of font programs (glyph widths against the font, the structure of embedded CMaps), ICC profile contents beyond the header, JPEG 2000 parameters, the size and nesting limits of 6.1.13, optional content configurations, digital signature rules and the extension schemas of XMP are not checked. Run veraPDF on your own files before you rely on the claim.

## Text recognition hook

The package's own OCR engine, [`@birchui/pdf/ocr`](https://docs.birchui.com/pdf/ocr.md), is built on this hook, and it is also the way to connect an engine of your own, for example for a script the bundled Latin model does not read. `recognizeText` hands each page without text to a callback and writes the words it returns as an invisible text layer, which makes a scan searchable, selectable and redactable by pattern:

```ts
import { openPdfDocument, type OcrPageImage, type OcrWord } from '@birchui/pdf/engine';

declare const scanBytes: Uint8Array;
declare function runOcr(image: OcrPageImage): Promise<OcrWord[]>;

const pdf = openPdfDocument(scanBytes);
const pages = await pdf.recognizeText({ recognizeText: runOcr });
console.info(pages.map((page) => `${page.pageIndex}: ${page.status}, ${page.words} words`));
const { bytes: searchable } = await pdf.save();
console.info(searchable.length, pdf.findText('invoice').length);
```

- The callback receives `{ pageIndex, width, height, data }` with RGBA pixels and returns words as `{ text, rect: [x1, y1, x2, y2] }` in pixels of that image, origin at the top left. To plug in a WebAssembly engine such as Tesseract, create its worker once, pass it an `ImageData` built from `data`, and map its word boxes to that shape.
- The image is the largest image on the page, decoded by the package, which is what a scanned page consists of. Pass `renderPage: (pageIndex) => ({ width, height, data, matrix })` to supply a rendering of the whole page instead; `matrix` maps the unit square to the page area the picture covers, `[pageWidth, 0, 0, pageHeight, 0, 0]` for a full page.
- Pages that already have text are skipped (`status: 'has-text'`) unless `includePagesWithText` is set. Pages without a usable image report `no-image`.
- Words are written along the direction of the picture: on a page with `/Rotate` 90, 180 or 270, or a scan placed turned on the page, the text matrix is turned by the same quarter, so the words read upright in the displayed page and `pdftotext`, search and selection return them line by line.
- Words are written with text rendering mode 3, stretched to their box. Latin text uses Helvetica; other scripts need `fonts` or `fontFallback`, and words no font can encode are left out and counted in `skippedWords`.
- `addTextLayer(pageIndex, words)` writes a layer from words you already have, with `rect` in page coordinates. A word reads upright on the page as displayed unless it carries `rotation: 0 | 90 | 180 | 270`, the direction of its baseline in page space, counter-clockwise. Both are undoable steps.
- Text extraction (`extractText`, `getPageText`, `findText`) builds lines along the baseline of runs turned by a quarter, so sideways text in any PDF comes back as words and lines and not as single letters.

## Export to Word and Excel

**Export text** on the Tools tab has a **Format** list: plain text, a Word document, or the tables of the document as an Excel workbook. From code:

```ts
const docx = await viewer.exportDocx({ pages: [0, 1] });
const xlsx = await viewer.exportTablesXlsx();
viewer.on('officeExport', ({ format, bytes, pages, tables }) => console.info(format, bytes.length, pages, tables));
```

The headless document has `exportDocx(options)`, `exportTablesXlsx(options)` and `getLayoutBlocks(options)`, which returns what the export is made of, and `@birchui/pdf/engine` exports `analyzeLayout`, `blocksText`, `blocksToDocx` and `tablesToXlsx` for your own writer.

The structure is read from the layout of the text, not from tags:

- **Headings**: a line set larger than the body size (the three largest sizes become levels 1 to 3), or a short line in bold that stands alone.
- **Lists**: a line that starts with a bullet, a dash or a number or letter followed by `.` or `)`; lines that continue an item stay with it.
- **Tables**: two or more consecutive rows whose cells line up in the same columns. Cells are read from left to right as they appear on the page. In the workbook each table is one sheet and a cell that is a plain number (`412.5`, not `1,250.00` or `007`) becomes a number.
- **Paragraphs**: everything else; lines that follow each other closely are joined.

Every character of the page text ends up in exactly one block, in the reading order of `getStructuredText`. On the seven real-world test files the text of the export equals the page text apart from white space, and LibreOffice opens the Word file and the workbook and reads the same text. The code is loaded when the export is first used.

Limits: pictures, colours, fonts, column layout, headers and footers as such, merged table cells, tables whose rows have different numbers of cells and tables drawn only with lines are not recognised; a table of a right-to-left document is exported in the order the columns appear on the page. `exportTablesXlsx` rejects, and the dialog says so, when no table is found.

## Related tools

- `splitPdf` and cropping: [Page tools](https://docs.birchui.com/pdf/page-tools.md).
- `optimizePdf` and flattening: [Saving](https://docs.birchui.com/pdf/saving.md).
- `encryptPdf` and `decryptPdf`: [Encryption and passwords](https://docs.birchui.com/pdf/encryption.md).
- Adding and editing page text and images: [Content editing](https://docs.birchui.com/pdf/content-editing.md).
