# PDF API and events

> Every option, method and event of the Birch UI PDF viewer, the headless document API and the standalone functions, with defaults and payloads.

The viewer, every type and the light helpers are exported from `@birchui/pdf`. The headless engine is exported from `@birchui/pdf/engine`, which contains no viewer code; the document functions in the second import below exist only there. Names that are not in the documentation are internal and can change without notice.

```ts
import { createPdfViewer, pdfViewerDefinition, PDF_VIEWER_EVENT_NAMES, pdfStyles, createFontRegistry, KEYBOARD_SHORTCUTS, DEFAULT_LABELS, REDACTION_PATTERNS } from '@birchui/pdf';
import { openPdfDocument, loadPdfDocument, encryptPdf, decryptPdf, signPdf, verifyPdfSignatures, addDocumentTimestamp, addValidationData, parsePkcs12, comparePdf, optimizePdf, splitPdf, imagesToPdf, checkArchiveReadiness } from '@birchui/pdf/engine';
```

## createPdfViewer(container, options)

Returns the shared widget contract (`element`, `update(partial)`, `on(event, listener)`, `destroy()`) plus the methods below. `on` returns a function that removes the listener. `update()` applies only the keys you pass and never recreates the viewer. It throws a `TypeError` when `container` is not an element.

### Options

| Option | Default | Description |
| --- | --- | --- |
| `document` | | `Uint8Array`, `ArrayBuffer` or `Blob` to open, or `{ url, httpHeaders?, withCredentials? }` or `{ rangeLoader }` for [progressive loading](https://docs.birchui.com/pdf/rendering.md#progressive-loading) |
| `rangeChunkSize` | `65536` | Bytes requested at a time in progressive loading |
| `allowFetch` | `false` | Let the viewer load a `{ url }` source with the global `fetch`. See [URL sources](https://docs.birchui.com/pdf/rendering.md#url-sources). |
| `fetchDocument` | | `({ url, range?, headers?, withCredentials, signal }) => Promise<{ bytes, total? }>`: your function that loads `{ url }` sources; it takes precedence over `allowFetch` |
| `renderPage` | | `(context: RenderPageContext) => void \| Promise<void>`, called instead of the default page paint |
| `toolbarPreset` | | `'viewer'`, `'reviewer'`, `'editor'`, `'form-filler'` or `'full'`; explicit options win |
| `sidebarPanels` | all | The sidebar panels that are offered |
| `shortcuts` | | `Partial<Record<ViewerCommand, string \| string[] \| false>>` merged over `KEYBOARD_SHORTCUTS` |
| `initialViewState` | | `Partial<PdfViewState>` applied when the first document is shown |
| `tabs` | `false` | Show a document tab strip; each tab keeps its own document, history and view state |
| `fileName` | `'document.pdf'` | Used for downloads, XFDF and the `save` event |
| `password` | | Password for an encrypted file |
| `mentions` | none | `{ search(query, { signal }), onMention?({ user, annotation, replyId? }), debounce? }`: `@` mentions in comments and replies from your own directory. See [Mentions](https://docs.birchui.com/pdf/annotations.md#mentions). |
| `onPasswordRequest` | built-in prompt | `({ isRetry, fileName }) => string \| null \| undefined`, or a promise of it. See [Encryption](https://docs.birchui.com/pdf/encryption.md). |
| `worker` | a worker where `Worker` and `OffscreenCanvas` exist | `true`, `false`, a `Worker` or a function that returns one. See [The render worker and render options](https://docs.birchui.com/pdf/rendering.md#the-render-worker-and-render-options). |
| `renderOptions` | | `{ renderLimits?, maxRenderMs?, substituteFont?, standardFonts?, predefinedCMaps? }` for the built-in engine |
| `renderer` | the built-in engine | Your own `PdfRenderer`, or a function that returns one or a promise of one |
| `licenseKey` | | Your license key |
| `injectStyles` | `true` | Inject the CSS; set `false` and import `@birchui/pdf/styles.css` instead |
| `theme` | `'auto'` | `'light'`, `'dark'` or `'auto'` |
| `invertPagesInDark` | `false` | Invert page colours |
| `height` | | Number of pixels or any CSS length |
| `ariaLabel` | `'PDF document'` | Accessible name of the viewer region |
| `toolbar` | all items | `false`, or an ordered list of `sidebar`, `pageNavigation`, `zoom`, `rotate`, `view`, `pointer`, `search`, `tools`, `undoRedo`, `print`, `download`, `theme`, `menu`, `separator`, `spacer`. See [Viewer](https://docs.birchui.com/pdf/viewer.md#toolbar). |
| `tools` | every tool except `formField` | Tools that exist in this viewer |
| `tool` | `'select'` | Initial tool |
| `toolGroup` | tab of `tool` | Task tab that is open at the start: `view`, `comment`, `edit`, `pages`, `forms`, `protect`, `tools`. The former ids `annotate`, `shapes`, `insert`, `measure` (Comment), `redact` (Protect) and `content` (Edit) still work |
| `ocr` | none | Turns on text recognition in the viewer: `{ model, worker, engine, languages, dpi, banner }`; see [Text recognition](https://docs.birchui.com/pdf/ocr.md#in-the-viewer) |
| `sidebar` | `'thumbnails'` | `false`, or the initial panel: `thumbnails`, `outline`, `annotations`, `fields`, `search`, `redaction`, `attachments`, `signatures` |
| `isSidebarOpen` | `true` | Start with the sidebar open. Below 720 px it starts closed unless this is `true`. |
| `initialPage` | `0` | Zero-based page to show first |
| `zoom` | `'auto'` | A number, `'fit-width'`, `'fit-page'` or `'auto'` |
| `minZoom`, `maxZoom` | `0.1`, `16` | Zoom limits |
| `scrollMode` | `'vertical'` | `'vertical'`, `'horizontal'` or `'page'` |
| `spread` | `'none'` | `'none'`, `'odd'` or `'even'` two-page spreads |
| `pageDirection` | `'ltr'` | Order of pages in spreads and horizontal scrolling |
| `pageGap` | `12` | Pixels between pages |
| `currentUser` | | A name, or `{ name, id?, isAdmin? }`: author of new annotations. A user edits their own annotations, an administrator everyone's. |
| `author` | `'Guest'` | Author name when `currentUser` is not set |
| `canEdit` | own annotations, or all for an administrator | `(annotation, user) => boolean`, replaces the default rule. See [Authors and permissions](https://docs.birchui.com/pdf/annotations.md#authors-and-permissions). |
| `readOnly` | `false` | Disable all editing; navigation, search and print still work |
| `ignorePermissions` | `false` | Do not enforce the permission flags of a protected document. See [Encryption](https://docs.birchui.com/pdf/encryption.md#what-permissions-mean). |
| `enableForms` | `true` | Show interactive form fields and the Form fields panel |
| `enablePageTools` | `true` | Show the page toolbar in the Pages panel and allow dragging pages |
| `enableFormDesigner` | `false` | Add the `formField` tool and the field property editor |
| `annotationDefaults` | | Per-type `color`, `opacity`, `strokeWidth`, `fillColor`, `fontSize` |
| `annotationPresets` | `[]` | Saved styles for the Presets menu of the style bar; see [Presets](https://docs.birchui.com/pdf/annotations.md#presets) |
| `stamps` | | Custom stamps: `{ name, label, color?, subtitle? }`; `label` and `subtitle` may be functions of `{ user, now, locale }` |
| `signatureStorage` | in memory | `{ load(), save(signatures) }` for saved electronic signatures |
| `trustedCertificates` | | Trust roots (DER bytes or PEM) for the Signatures panel and `verifySignatures()` |
| `snapping` | `true` | Snap drawn, moved and resized points to the page content (path corners and edges, text baselines and text box corners) and to other annotations |
| `keepToolSelected` | `false` | Keep the sticky note tool, and a text markup tool chosen over a text selection, selected after use instead of returning to the Select tool. See [Which tools stay selected](https://docs.birchui.com/pdf/annotations.md#which-tools-stay-selected). |
| `fonts` | | `PdfFontSource[]` passed to the document session, so non-Latin annotations, form values and edited or added page text are embedded on save |
| `annotationScope` | `'markup'` | `'all'` also lists the links and the file attachment, sound and media annotations of the file as annotations |
| `allowFileDrop` | `false` | Open a PDF (or, unless `convertMail` is `false`, an email file) that is dropped onto the viewer, and offer to insert a dropped image as a page |
| `fillInitials` | none | The initials the **Fill and sign** tool places; without it the viewer asks once and emits `fillInitialsChange` |
| `fileConverters` | none | Converters by file extension (`{ docx: (bytes, file) => pdfBytes }`) for dropped and opened files of other formats; see [Opening Word and Excel files](https://docs.birchui.com/pdf/customization.md#opening-word-and-excel-files) |
| `welcome` | `true` | Show the welcome box with an **Open a PDF** button while no document is loaded; `false` keeps the plain message |
| `decodeImage` | browser | `(bytes, mimeType) => { width, height, data }` for image formats the package does not read (WebP, SVG and others); see [Image formats](https://docs.birchui.com/pdf/content-editing.md#image-formats) |
| `printResolution` | `150` | Default resolution in dpi when pages are printed as images |
| `locale` | `'en'` | Locale for plural rules and date formats |
| `labels` | English | Partial `PdfViewerLabels` |
| `localeText` | | Translations with `pdf.` keys. See [Translation](https://docs.birchui.com/pdf/accessibility.md#translation). |
| `rtl` | from `dir` | Mirror the interface |
| `maxCanvasPixels` | `16777216` | Upper bound for one page canvas |
| `maxRenderPixels` | `64000000` | Canvas budget shared by off-screen neighbour pages |
| `pixelRatio` | `devicePixelRatio` | Rendering resolution multiplier |
| `placeholders` | `true` | Prepare low-resolution previews of nearby pages |
| `highlightRequiredFields` | `true` | Frame required form fields in red |
| `createId`, `now` | | Supply your own annotation ids and clock |

### Methods

| Group | Methods |
| --- | --- |
| Document | `ready`, `load(source, { fileName, password })`, `save({ mode, compress, flatten })`, `download(fileName?)`, `isModified()`, `print({ pages, resolution, annotations, mode })` |
| Navigation | `getPageCount()`, `getPages()`, `getCurrentPage()`, `goToPage(index, { point })`, `nextPage()`, `previousPage()`, `getPageLabel(index)`, `getPageText(index)` |
| View | `getZoom()`, `setZoom(zoom)`, `zoomIn()`, `zoomOut()`, `zoomToRect(index, rect)`, `getRotation()`, `rotateView(delta?)`, `getScrollMode()`, `setScrollMode(mode)`, `getSpread()`, `setSpread(spread)`, `enterPresentation()`, `exitPresentation()`, `toggleFullscreen()`, `openSidebar(panel?)`, `closeSidebar()`, `getRenderStats()` |
| Search | `search(query, { caseSensitive, wholeWord, regex, diacriticSensitive })`, `searchNext()`, `searchPrevious()`, `clearSearch()` |
| Tools | `getTool()`, `setTool(tool, { stamp, field })` |
| Annotations | `getAnnotations(page?)`, `getAnnotation(id)`, `addAnnotation(input)`, `addAnnotations(inputs)`, `addTextMarkup(type, page, rects, extra?)`, `updateAnnotation(id, patch)`, `removeAnnotation(id \| ids)`, `scrollToAnnotation(id)`, `addSignature(draft, { pageIndex, rect })`, `setAuthor(name)` |
| Selection | `selectAnnotation(id \| null)`, `selectAnnotations(ids)`, `getSelectedAnnotation()`, `getSelectedAnnotations()` |
| Comments | `addReply(id, { contents, author? })`, `updateReply(id, replyId, contents)`, `removeReply(id, replyId)`, `canEditAnnotation(id)`, `exportCommentSummary({ format, sort?, author?, type?, status?, pages?, includeReplies?, title?, fonts? })`, `downloadCommentSummary(options)` |
| History | `undo()`, `redo()`, `canUndo()`, `canRedo()` |
| Loading state and layers | `isEditable()`, `getLayers()`, `setLayerVisibility(id, isVisible)` |
| Commands and view state | `runCommand(command)`, `getCommands()`, `openCommandPalette()`, `getViewState()`, `setViewState(state)` |
| Tabs | `openTab(source, { fileName, password })`, `closeTab(id)`, `activateTab(id)`, `getTabs()` |
| Text | `getPageText(page)`, `getPageTextItems(page)`, `readAloud({ fromPage, onText, lang, rate })`, `stopReadAloud()`, `captureRegion(page, rect, { scale })` |
| Redaction | `markRedactions(query, options?)` with a text, a `RegExp`, `{ text }`, `{ pattern }` or `{ preset }`, `applyRedactions(ids?)` |
| Forms | `getFormFields()`, `getFormValues()`, `setFormValue(name, value)`, `setFormValues(values)`, `resetForm()`, `addFormField(input)`, `updateFormField(name, patch)`, `removeFormField(name)`, `getTabOrder(page)`, `setTabOrder(page, mode)`, `setFieldTabOrder(page, widgetIds)` |
| Page content | `getTextRuns(page)`, `editPageText(page, run, text)`, `deletePageText(page, run)`, `movePageText(page, run, { dx, dy })`, `addPageText(page, options)`, `getPageImages(page)`, `extractImages(page, { renderFallback }?)`, `prepareImage(bytes, options?)`, `addPageImage(page, { data, rect })`, `movePageImage(page, image, move)`, `replacePageImage(page, image, data)`, `deletePageImage(page, image)`; the editing methods return a promise that resolves after the page has been rendered again |
| Links and attachments | `followLink(id)`, `getAnnotationAttachment(id)`, `downloadAnnotationAttachment(id)`, `openAttachment(name)`, `getCollection()`; see [Attachments and portfolios](https://docs.birchui.com/pdf/attachments.md) |
| Document tools | `addWatermark(options)`, `addHeaderFooter(options)`, `addBatesNumbers(options?)`, `cropPages(indices, box \| null)`, `flatten(mode?)`, `getOutline()`, `setOutline(items)`, `getMetadata()`, `setMetadata(patch)`, `getAttachments()`, `addAttachment(input)`, `removeAttachment(name)`, `getPageLabels()`, `setPageLabels(ranges)` |
| Security | `getPermissions()`, `isAllowed(permission)`, `getEncryption()` |
| Signatures | `getSignatures()`, `verifySignatures()`, `signDocument(options)` |
| Form checks and data | `validateForm()`, `resetForm(names?)`, `exportFormData(format)`, `importFormData(data, format?)`, `downloadFormData(format)` |
| Page organizer | `openPageOrganizer()`, `closePageOrganizer()`, `movePages(indices, target)`, `reversePages(indices?)`, `duplicatePages(indices)`, `insertPagesFrom(source, pageIndexes, at?)`, `insertImagePages(images, at?, options?)`, `resizePages(indices, options)`, `getPageBoxes(index)`, `setPageBoxes(indices, boxes)`, `splitDocument(options)`, `openMergeDialog()`, `mergeFiles(inputs, options?)`, `replacePages(indices, source, sourceIndices?)`, `interleaveDocument(source, options?)`, `findBlankPages(pages?)`, `deleteBlankPages(pages?)`, `addPageNumbers(options?)`, `removePageNumbers(pages?)`, `imposePages(options)`; see [Page tools](https://docs.birchui.com/pdf/page-tools.md#from-code) |
| Compare | `compareWith(other, { fileName, password, view })` |
| Pages | `movePage(from, to)`, `rotatePages(indices, degrees?)`, `deletePages(indices)`, `insertBlankPage(at, size?)`, `mergeDocument(source, at?)`, `extractPages(indices, { deleteExtracted? })` |
| Exchange | `exportXfdf()`, `importXfdf(xml, { replace })`, `exportAnnotationsJson()`, `importAnnotationsJson(json, { replace })`, `exportAnnotationsFdf({ includeAppearances })`, `importAnnotationsFdf(bytes, { replace })`, `getAnnotationPresets()`, `setAnnotationPresets(presets)` |
| Sync | `subscribeAnnotationChanges(listener)`, `applyRemoteChanges({ upsert, remove })`; used by `createAnnotationSync` |

Methods that need a document throw `Error('No document is open…')` before one is loaded; the getters return empty values instead. `save`, `download`, `print`, `search`, `load`, `mergeDocument`, `extractPages`, `getPageText`, `getSignatures`, `verifySignatures`, `signDocument`, `compareWith` and the document tools that change the document (`addWatermark`, `addHeaderFooter`, `addBatesNumbers`, `cropPages`, `flatten`, `setOutline`, `setMetadata`, `addAttachment`, `removeAttachment`, `setPageLabels`) return promises. The document tools resolve when the viewer has switched to the changed page content; each is one undo step. See [Document tools](https://docs.birchui.com/pdf/document-tools.md#in-the-viewer).

On a protected document, a method that the permission flags deny throws a `PdfPermissionError`, or rejects with one when it returns a promise. Encryption and content editing are not methods of the viewer; use the menu, or a headless document and `load()` the result.

### Events

| Event | Payload |
| --- | --- |
| `documentLoad` | `{ pageCount, fileName, title }`. Also fires when the viewer reloads the document after a signature. |
| `documentChange` | `{ reason }`, after a document tool, or an undo or redo of one, when the viewer has switched to the changed page content. `reason` is `metadata`, `outline`, `attachments`, `watermark`, `headerFooter`, `bates`, `crop`, `pageLabels`, `pageText`, `pageImage`, `flatten` or `history`. |
| `documentError` | `{ error, message }` |
| `documentPreview` | `{ pageCount, fileName }`, when the first page of a progressively loaded document is visible and the viewer is still view-only |
| `layersChange` | `{ layers }` |
| `viewStateChange` | `{ state }`, at most once every 150 ms |
| `tabChange` | `{ tabs, activeId }` |
| `pageChange` | `{ pageIndex, previousPageIndex, pageCount }` |
| `zoomChange` | `{ zoom, mode }` |
| `annotationPresetsChange` | `{ presets }`, after a preset was saved or removed in the interface |
| `layoutChange` | `{ scrollMode, spread }` |
| `presentationChange` | `{ isPresenting }` |
| `toolChange` | `{ tool }` |
| `searchResult` | `{ query, total, current }` |
| `annotationAdd` | `{ annotations, source }` |
| `annotationChange` | `{ changes: [{ before, after }], source }` |
| `annotationRemove` | `{ annotations, source }` |
| `annotationSelect` | `{ annotation, annotations }`; `annotation` is the last selected one, or `null` |
| `formFieldChange` | `{ name, value, previousValue, source }` |
| `pagesChange` | `{ pages, reason }` |
| `historyChange` | `{ canUndo, canRedo }` |
| `formValidation` | `{ issues, isValid }`, after `validateForm()` or **Check the form** |
| `formSubmit` | `{ url, method, format, body, contentType, fieldNames, fieldName? }`, when a submit button is used. Nothing is sent. |
| `formReset` | `{ names, changed }` |
| `formDataExport` | `{ format, data, fileName }` |
| `pagesSplit` | `{ parts }`, each with `name`, `pageIndexes` and `bytes` |
| `filesMerge` | `{ files, pageCount, result, bytes? }` after the merge dialog or `mergeFiles`; `result` is `inserted` or `new` |
| `attachmentOpen` | `{ name, mimeType, size, data, source, pageIndex?, relationship?, description? }`, when the user opens an attachment or `openAttachment(name)` is called; see [Attachments](https://docs.birchui.com/pdf/attachments.md#opening-a-file-in-your-application) |
| `printProgress` | `{ page, total, isDone, isCancelled }` |
| `save` | `{ bytes, mode, fileName }` |

`source` is `user`, `api`, `history` or `import`. `PDF_VIEWER_EVENT_NAMES` lists the event names.

## openPdfDocument(bytes, options) and loadPdfDocument(bytes, options)

The headless API has no DOM dependency. `openPdfDocument` is synchronous; `loadPdfDocument` returns a promise and decrypts password-protected files. Both return a `PdfDocument`.

| `OpenPdfOptions` | Default | Description |
| --- | --- | --- |
| `author` | `'Guest'` | Author of new annotations and replies |
| `password` | | For `loadPdfDocument` |
| `fonts` | | `{ name, data }[]` TrueType or OpenType fonts for non-Latin text. See [Fonts](https://docs.birchui.com/pdf/fonts.md). |
| `annotationDefaults` | | Per-type style defaults |
| `historyLimit` | `200` | Number of undo steps kept |
| `readAnnotations` | `true` | `false` skips reading existing annotations |
| `annotationScope` | `'all'` | `'markup'` leaves links, attachments and media annotations out of the model, as the viewer does |
| `ignorePermissions` | `false` | Do not enforce the permission flags of a protected document |
| `authorId` | | Stored as `customData.authorId` on new annotations of this author |
| `createId`, `now` | | Your own ids and clock |

| Group | Members of `PdfDocument` |
| --- | --- |
| State | `pageCount`, `isModified`, `isEncrypted`, `isLocked`, `hasSignatures`, `certification`, `permissions`, `encryption`, `isAllowed(permission)` |
| Pages | `getPages()`, `movePage(from, to)`, `movePages(indices, target)`, `rotatePages(indices, degrees?)`, `deletePages(indices)`, `insertBlankPage(at, size?)`, `mergeDocument(bytes, at?)`, `mergeEncryptedDocument(bytes, password?, at?)`, `extractPages(indices, { deleteExtracted? })`, `replacePages(indices, bytes, sourceIndices?)`, `interleaveDocument(bytes, options?)`, `mergeFiles(inputs, options?)`, `findBlankPages(pages?)`, `deleteBlankPages(pages?)`, `addPageNumbers(options?)`, `removePageNumbers(pages?)`, `findPageNumbers(pages?)`, `impose(options)`, `cropPages(indices, box \| null)`, `getPageLabels()`, `setPageLabels(ranges)` |
| Annotations | `setAuthor(name)`, `getAnnotations(page?)`, `addAnnotation(input)`, `addAnnotations(inputs)`, `updateAnnotation(id, patch)`, `removeAnnotation(id \| ids)`, `addReply`, `updateReply`, `removeReply`, `addTextMarkup(type, page, quads, extra?)`, `uprightPlacement(page, rect)`, `getNamedDestinations()`, `getAnnotationAttachment(id)` |
| Forms | `getFormFields()`, `getFormField(name)`, `getFormValues()`, `setFormValue(name, value)`, `setFormValues(values)`, `resetForm(names?, { exclude? })`, `addFormField(input)`, `updateFormField(name, patch)`, `removeFormField(name)`, `getTabOrder(page)`, `setTabOrder(page, mode)`, `setFieldTabOrder(page, widgetIds)` |
| Form validation and scripts | `validateFormField(name, value?)`, `validateFormFieldIssue(name, value?)`, `validateForm()`, `getFormState()`, `filterKeystroke(name, currentValue, change, selStart, selEnd?)`, `describeFieldScripts(name)` |
| Form actions | `getFieldActions(name)`, `buildSubmitPayload(action)`, `submitForm(action, fieldName?)` |
| Form data | `exportFormFdf(fileName?)`, `importFormFdf(bytes)`, `exportFormXfdf(fileName?)`, `importFormXfdf(xml)`, `exportFormJson({ flat? })`, `importFormJson(json)`, `exportFormXml()`, `importFormXml(xml)` |
| Form design | `updateFormFields(names, patch)`, `duplicateField(name, { offset?, pageIndex?, newName? })`, `alignFields(targets, mode)`, `distributeFields(targets, direction)`, `sizeFields(targets, mode)`, `getCalculationOrder()`, `setCalculationOrder(names)`, `setFieldCalculation(name, calculation)`, `getSignatureFields()`, `fillSignatureField(name, signature)` |
| Text and redaction | `extractText(page)`, `getPageText(page)`, `getStructuredText(page, options?)`, `extractTextItems(page, options?)`, `findText(query, { pages, caseSensitive, wholeWord })`, `markRedactions(query, options?)`, `applyRedactions(ids?, { decodeImage }?)`, `applyRedactionsAsync(ids?, { decodeImage }?)`, `getRedactionImages(ids?)`, `getAppliedRedactions(page)` |
| Page content | `getTextRuns(page)`, `editPageText(page, run, text)`, `deletePageText(page, run)`, `movePageText(page, run, { dx, dy })`, `addPageText(page, options)`, `getPageImages(page)`, `extractImages(page)`, `prepareImage(bytes, options?)`, `movePageImage(page, image, move)`, `replacePageImage(page, image, data)`, `deletePageImage(page, image)`, `addPageImage(page, options)`, `getPageGeometry(page, options?)` |
| Compare | `compareWith(other, options?)` |
| Document tools | `getMetadata()`, `setMetadata(patch)`, `getOutline()`, `setOutline(items)`, `getAttachments()`, `addAttachment(input)`, `removeAttachment(name)`, `getCollection()`, `addWatermark(options)`, `addHeaderFooter(options)`, `addBatesNumbers(options)`, `flatten(mode?)` |
| Security | `encrypt(options)`, `decrypt()`, `getSignatures()`, `verifySignatures({ trustedRoots, now, ocsps, crls, checkRevocation, requireRevocation })` |
| History and saving | `undo()`, `redo()`, `canUndo()`, `canRedo()`, `canSaveIncrementally()`, `save({ mode, compress, flatten })` |
| Exchange | `exportXfdf(fileName?)`, `importXfdf(xml, { replace })`, `exportAnnotationsJson()`, `importAnnotationsJson(json, { replace })` |
| Events | `on(event, listener)` |

| Headless event | Payload |
| --- | --- |
| `annotationAdd`, `annotationChange`, `annotationRemove`, `formFieldChange` | As in the viewer |
| `formFieldsChange` | `{ added, changed, removed, source }`: names of fields that were designed, not filled |
| `formReset` | `{ names, changed, source }`: the fields a reset covered and the ones whose value changed |
| `formSubmit` | `{ action, payload, fieldName? }`: a submit payload built by `submitForm`; nothing is sent |
| `pagesChange` | `{ pages, reason }` with `move`, `rotate`, `delete`, `insert`, `merge`, `redaction`, `crop`, `content` or `history` |
| `documentChange` | `{ reason }` with `metadata`, `outline`, `attachments`, `watermark`, `headerFooter`, `bates`, `crop`, `pageLabels`, `pageText`, `pageImage`, `flatten` or `history` |
| `historyChange` | `{ canUndo, canRedo, undoLabel, redoLabel }` |

## Standalone functions

| Function | Returns | Page |
| --- | --- | --- |
| `signPdf(bytes, options)` | `Promise<Uint8Array>` | [Signatures](https://docs.birchui.com/pdf/signatures.md#signing) |
| `verifyPdfSignatures(bytes, { trustedRoots, now, password, ocsps, crls, checkRevocation, requireRevocation })` | `Promise<PdfSignatureVerification[]>` | [Signatures](https://docs.birchui.com/pdf/signatures.md#validation) |
| `addDocumentTimestamp(bytes, { timestamp, fieldName?, placeholderSize?, password? })` | `Promise<Uint8Array>` | [Signatures](https://docs.birchui.com/pdf/signatures.md#timestamps) |
| `addValidationData(bytes, { certificates?, ocsps?, crls?, fetch?, password?, now? })` | `Promise<Uint8Array>` | [Signatures](https://docs.birchui.com/pdf/signatures.md#long-term-validation) |
| `parsePkcs12(bytes, password?)`, `importPkcs12PrivateKey(contents, hash?)` | `Promise<Pkcs12Contents>`, `Promise<CryptoKey>`; errors are `Pkcs12Error` | [Signatures](https://docs.birchui.com/pdf/signatures.md#pkcs12-files) |
| `pemToDer`, `derToPem`, `pemBlocks`, `certificateToDer` | bytes or text | [Signatures](https://docs.birchui.com/pdf/signatures.md#pem-helpers) |
| `encryptPdf(bytes, options)`, `decryptPdf(bytes, password?)` | `Promise<Uint8Array>` | [Encryption](https://docs.birchui.com/pdf/encryption.md) |
| `permissionsToFlags(permissions)`, `permissionsFromFlags(flags)` | number, `PdfPermissions` | [Encryption](https://docs.birchui.com/pdf/encryption.md) |
| `comparePdf(a, b, options)`, `comparePageTexts(a, b, options)` | `PdfComparison` | [Compare](https://docs.birchui.com/pdf/compare.md) |
| `comparePdfAsync(a, b, { password, otherPassword, …options })` | `Promise<PdfComparison>` | [Compare](https://docs.birchui.com/pdf/compare.md#password-protected-files) |
| `decodeJpeg(bytes, options?)` | `JpegImage` | [Redaction](https://docs.birchui.com/pdf/redaction.md#images-under-a-redaction) |
| `quadPointsFromQuads(quads)` | `number[]` | [Content editing](https://docs.birchui.com/pdf/content-editing.md#reading-text-in-reading-order) |
| `comparisonAnnotations(changes, options)` | `{ a, b }` annotation inputs | [Compare](https://docs.birchui.com/pdf/compare.md) |
| `optimizePdf(bytes, options)` | `Promise<{ bytes, report }>` | [Saving](https://docs.birchui.com/pdf/saving.md#optimizing) |
| `splitPdf(bytes, options)` | `Promise<SplitPart[]>` | [Page tools](https://docs.birchui.com/pdf/page-tools.md#splitting) |
| `imagesToPdf(images, options)` | `Promise<Uint8Array>` | [Document tools](https://docs.birchui.com/pdf/document-tools.md#images-to-pdf) |
| `checkArchiveReadiness(bytes)` | `ArchiveReport` | [Document tools](https://docs.birchui.com/pdf/document-tools.md#archive-readiness-check) |
| `createFontRegistry(fonts)` | `FontRegistry` | [Fonts](https://docs.birchui.com/pdf/fonts.md) |
| `formatBatesNumber(index, options)` | string | [Document tools](https://docs.birchui.com/pdf/document-tools.md#bates-numbering) |
| `annotationsToXfdf(annotations, fields?, fileName?)`, `parseXfdf(xml)` | string, `{ annotations, fields }` | [Annotations](https://docs.birchui.com/pdf/annotations.md#exchange-formats) |
| `annotationsToJson(annotations)`, `annotationsFromJson(value)` | `AnnotationsJson`, annotation inputs | [Annotations](https://docs.birchui.com/pdf/annotations.md#exchange-formats) |
| `annotationsToFdf(annotations, options?)`, `parseAnnotationsFdf(bytes)` | `Uint8Array`, `{ annotations, fileName? }` | [Annotations](https://docs.birchui.com/pdf/annotations.md#fdf) |
| `rotateAnnotation`, `setAnnotationRotation`, `annotationBounds`, `annotationCorners`, `rotatedBounds`, `rotatedCorners`, `toUnrotatedPoint`, `toRotatedPoint`, `rotationHandlePoint`, `rotationFromPointer`, `resizeRotated`, `uprightPlacement`, `uprightRotation`, `unrotatedRectFromBounds`, `normalizeDegrees`, `hitTestAnnotation` | patches, points, rectangles | [Annotations](https://docs.birchui.com/pdf/annotations.md#rotation) |
| `parseRichText`, `richTextToXhtml`, `richTextToPlain`, `plainToRichText`, `normalizeRichText`, `layoutRichText`, `richTextDefaultStyle`, `annotationRichDefaults`, `isUniformRichText` | paragraphs, text, lines | [Annotations](https://docs.birchui.com/pdf/annotations.md#rich-text-in-text-boxes) |
| `isSafeLinkUri(uri)`, `linkUriScheme(uri)`, `describeLinkAction(action)` | boolean, string | [Annotations](https://docs.birchui.com/pdf/annotations.md#links) |
| `measureDetails(annotation)`, `measureValue(annotation)`, `arcThrough`, `arcPoints`, `circleThrough`, `angleBetween`, `quadsFromQuadPoints` | numbers and geometry | [Annotations](https://docs.birchui.com/pdf/annotations.md#count-arc-and-angle-measurements) |
| `annotationPermissions(annotation, user, options?)`, `isAnnotationOwner(annotation, user)`, `annotationFlags(annotation)` | `AnnotationPermissions`, boolean, number | [Annotations](https://docs.birchui.com/pdf/annotations.md#flags-and-permissions) |
| `presetFromAnnotation`, `annotationInputFromPreset`, `presetStyle`, `annotationPresetsToJson`, `annotationPresetsFromJson` | presets and inputs | [Annotations](https://docs.birchui.com/pdf/annotations.md#presets) |
| `createAnnotationSync(document, options)`, `createPresenceTracker(options?)`, `presenceMessage`, `leaveMessage`, `toSyncJson`, `fromSyncJson`, `compareSyncClocks` | `AnnotationSync`, `PresenceTracker` | [Annotations](https://docs.birchui.com/pdf/annotations.md#real-time-sync) |
| `createFormSync(host, options)`, `createPageSync(host, options)`, `formSyncHost(document)`, `pageSyncHost(document)`, `createSyncChannel(transport, options?)`, `positionBetween`, `originalPageId` | `FormSync`, `PageSync`, sync hosts, `AnnotationSyncChannel` | [Collaboration](https://docs.birchui.com/pdf/collaboration.md) |
| `isReadOnlyType(type)`, `isMediaType(type)`, `mimeTypeForFileName(name)` | boolean, string | [Annotations](https://docs.birchui.com/pdf/annotations.md#attachments-and-media) |
| `formatFieldValue(field, value?)`, `validateFieldValue(field, value)` | string, message or `undefined` | [Forms](https://docs.birchui.com/pdf/forms.md) |
| `parseFormatScript(script)`, `parseCalculateScript(script)`, `parseValidateScript(script)` | `FieldFormat`, `FieldCalculation`, `FieldRange` or `undefined` | [Forms](https://docs.birchui.com/pdf/forms.md#scripts-that-run) |
| `classifyScript(trigger, source)`, `describeScripts(field)`, `RECOGNISED_FUNCTIONS` | `{ status, kind, source }`, one per trigger, the recognised Acrobat function names | [Forms](https://docs.birchui.com/pdf/forms.md#scripts-that-run) |
| `checkFieldValue(field, value, resolve?)`, `formatFormMessage(key, params?, messages?)`, `FORM_MESSAGES` | `{ code, key, params, message }` or `undefined`, string, the default messages | [Forms](https://docs.birchui.com/pdf/forms.md#validation) |
| `filterFieldKeystroke(field, currentValue, change, selStart, selEnd?)` | `{ isAccepted, value, selStart, selEnd, key? }` | [Forms](https://docs.birchui.com/pdf/forms.md#keystroke-filtering) |
| `fieldKind(field)` | the field type, or `'barcode'` | [Forms](https://docs.birchui.com/pdf/forms.md#field-features) |
| `readImageInfo(bytes)` | `{ data, mimeType, width, height }` for PNG and JPEG; throws `ImageFormatError` otherwise | |
| `prepareImage(bytes, options?)`, `decodeImageFile(bytes, options?)` | Promise of a PNG or JPEG `{ data, mimeType, width, height }`; promise of RGBA pixels `{ width, height, data }` | [Content editing](https://docs.birchui.com/pdf/content-editing.md#image-formats) |
| `detectImageFormat(bytes)`, `imageMimeType(format)` | `'png'`, `'jpeg'`, `'gif'`, `'bmp'`, `'tiff'`, `'webp'`, `'svg'` or `undefined`; the media type of a format | [Content editing](https://docs.birchui.com/pdf/content-editing.md#image-formats) |
| `ATTACHMENT_RELATIONSHIPS` | the eight `AttachmentRelationship` values | [Attachments](https://docs.birchui.com/pdf/attachments.md#relationships-and-pdfa-3) |
| `shortcutFor(event, isPresenting?)` | command name or `undefined` | [Keyboard shortcuts](https://docs.birchui.com/pdf/keyboard.md) |

Geometry helpers for your own tools: `quadPointsFromRects(rects)`, `rectsFromQuadPoints(quadPoints)`, `mergeLineRects(rects, gap?)`, `smoothStroke(points)`, `simplifyPath(points, tolerance?)`, `polylineLength(points, isClosed?)`, `polygonArea(points)`, `formatMeasurement(annotation)` and `viewportTransform(box, rotation, scale)`, which returns the matrix from PDF user space to screen pixels.

Constants: `KEYBOARD_SHORTCUTS`, `DEFAULT_LABELS`, `DEFAULT_STYLES`, `STAMP_LABELS`, `STAMP_COLORS`, `REDACTION_PATTERNS`, `REDACTION_PATTERN_NAMES`, `PDF_VIEWER_EVENT_NAMES` and `pdfStyles` (the CSS as a string, for a shadow root).

Errors: `PdfSyntaxError`, `PdfWriteError`, `PdfPasswordError` (with `reason`), `PdfCryptoUnavailableError`, `ImageFormatError`, `ImageDecoderRequiredError` (an `ImageFormatError` with `mimeType`) and `FontFormatError`.

## The annotation model

```ts
interface PdfAnnotation {
  id: string;
  type: AnnotationType;
  pageIndex: number;
  rect: [x1: number, y1: number, x2: number, y2: number];
  color: string;
  opacity: number;
  strokeWidth: number;
  author: string;
  createdAt: string;
  modifiedAt: string;
  contents?: string;
  replies?: AnnotationReply[];
  status?: 'none' | 'accepted' | 'rejected' | 'cancelled' | 'completed';
  fillColor?: string;
  dashed?: boolean;
  borderStyle?: 'solid' | 'dashed' | 'dotted' | 'cloudy';
  rotation?: number;
  quadPoints?: number[];
  inkList?: PdfPoint[][];
  vertices?: PdfPoint[];
  line?: [PdfPoint, PdfPoint];
  lineEndings?: [LineEnding, LineEnding];
  text?: string;
  fontSize?: number;
  fontColor?: string;
  textAlign?: 'left' | 'center' | 'right';
  fontFamily?: 'Helvetica' | 'Times' | 'Courier';
  calloutLine?: PdfPoint[];
  groupId?: string;
  icon?: NoteIcon;
  stamp?: BuiltInStamp | string;
  stampLabel?: string;
  image?: { data: Uint8Array; mimeType: 'image/png' | 'image/jpeg'; width: number; height: number };
  signatureKind?: 'drawn' | 'typed' | 'image';
  measureScale?: { pdfUnits: number; realUnits: number; unit: string; precision?: number };
  overlayText?: string;
  url?: string;
  destinationPage?: number;
  isLocked?: boolean;
  isHidden?: boolean;
  isReadOnly?: boolean;
  isContentsLocked?: boolean;
  isNoView?: boolean;
  isPrintable?: boolean;
  richText?: RichTextParagraph[];
  action?: LinkAction;
  highlightMode?: 'none' | 'invert' | 'outline' | 'push';
  label?: string;
  iconName?: string;
  attachment?: {
    fileName: string;
    mimeType?: string;
    description?: string;
    size?: number;
    data?: Uint8Array;
    relationship?: AttachmentRelationship;
  };
  customData?: Record<string, unknown>;
}
```

`AnnotationType` is one of `highlight`, `underline`, `strikeout`, `squiggly`, `note`, `freeText`, `ink`, `rectangle`, `ellipse`, `line`, `arrow`, `polygon`, `polyline`, `distance`, `perimeter`, `area`, `count`, `arc`, `angle`, `stamp`, `image`, `signature`, `redaction`, `link`, `fileAttachment`, `sound`, `movie`, `screen`, `richMedia` and `media3d`.

```ts
interface RichTextRun {
  text: string;
  bold?: boolean;
  italic?: boolean;
  underline?: boolean;
  strikethrough?: boolean;
  color?: string;
  fontSize?: number;
  fontFamily?: string;
}
interface RichTextParagraph {
  runs: RichTextRun[];
  align?: 'left' | 'center' | 'right';
}
type LinkAction =
  | { kind: 'uri'; uri: string }
  | { kind: 'goto'; pageIndex: number; fit?: LinkFit; left?: number; top?: number; right?: number; bottom?: number; zoom?: number }
  | { kind: 'named'; name: string }
  | { kind: 'other'; actionType: string; name?: string };
```

`AnnotationInput` is the same with only `type` and `pageIndex` required; `AnnotationPatch` is any subset without `id`. `customData` is yours: it must be JSON-serialisable, and it is kept in the saved PDF (in a private key) and in XFDF and JSON exports.

## Document tools added to the viewer

| Method | Result |
| --- | --- |
| `recognizeText({ pages, includePagesWithText, language, signal, onProgress })` | Runs text recognition and resolves with one `{ pageIndex, status, words }` per page; needs the `ocr` option |
| `getOcrState(pageIndex)` | `'running'`, `'recognized'`, `'failed'`, `'no-text'` or `undefined` |
| `optimizeCopy(preset)` | `{ bytes, before, after }` for `'lossless'`, `'balanced'` or `'smallest'`; the open document is not changed |
| `exportPageImages({ pages, format, dpi, quality })` | One `{ pageIndex, fileName, mimeType, data }` per page, PNG or JPEG |
| `exportText({ pages, pageBreaks })` | The text of the pages as one string |
| `sanitize({ metadata, hiddenLayers, attachments, scripts, comments })` | Removes the chosen kinds of hidden information, reloads the cleaned document and resolves with the report |
| `getInitialView()`, `setInitialView(view)` | Page mode, page layout, opening page, zoom and title bar preference stored in the file |

Events: `textRecognition` (`{ pages, isCancelled }`), `pagesExport` (`{ format, files }`), `textExport` (`{ text, pages }`) and `documentSanitize` (`{ report }`).
