# Comparing documents

> Compare two PDF files page by page and word by word with comparePdf, detect added, removed and reordered pages and moved text, and show the result in the viewer's compare view with viewer.compareWith, including a pixel-level visual comparison.

`comparePdf` takes two files and returns what changed between them. It runs without a DOM, so it works in Node, in a worker and in the browser, and it uses the same text extraction as search and redaction.

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

const signed = await readFile('services-agreement-fabrikam-2026-signed.pdf');
const draft = await readFile('services-agreement-fabrikam-2026-draft-3.pdf');

const result = comparePdf(draft, signed, { annotations: true });

console.info(result.summary);
for (const page of result.pages) {
  console.info(page.status, page.pageIndexA, page.pageIndexB, page.changes.length);
}
```

The first argument is the older file (side A) and the second the newer one (side B).

## Pages

Pages are aligned by their text before any words are compared, so an inserted page does not turn every later page into a change. Each entry of `result.pages` has a `status`:

| Status      | Meaning                                                                                     |
| ----------- | ------------------------------------------------------------------------------------------- |
| `unchanged` | The page has the same text on both sides and sits in the same relative position.            |
| `changed`   | The pages are similar enough to be the same page, and `changes` lists the differences.      |
| `added`     | The page exists only in B. Its whole text is one `inserted` change.                         |
| `removed`   | The page exists only in A. Its whole text is one `deleted` change.                          |
| `moved`     | The page appears at a different position. If it was also edited, `changes` lists the edits. |

`pageIndexA` and `pageIndexB` are zero-based and missing on the side where the page does not exist. `similarity` is between 0 and 1. Entries are in reading order of B, with removed pages placed where they used to be.

Two pages count as the same page when at least 40% of their words match. Change this with `pageSimilarityThreshold`.

## Text changes

Every change has a `type`, the `text`, a `wordCount` and positions in PDF user space:

- `deleted`: `pageIndexA` and `rects` on side A.
- `inserted`: `pageIndexB` and `rects` on side B.
- `moved`: the same run of words was removed in one place and added in another, on the same page or on another one. `pageIndexA` and `fromRects` give the old place, `pageIndexB` and `rects` the new one.

`rects` holds one rectangle per line, so a change that wraps over two lines has two. `result.changes` is the flat list for the whole document.

A run counts as moved when at least four consecutive words match exactly; set `minMoveWords` to change that. Shorter runs are reported as a deletion and an insertion.

## Options

| Option                    | Default | Effect                                                                                |
| ------------------------- | ------- | ------------------------------------------------------------------------------------- |
| `ignoreCase`              | `false` | `Total` and `TOTAL` are the same word.                                                |
| `ignoreWhitespace`        | `false` | Words that were only split or joined (`ware house` and `warehouse`) are not a change. |
| `annotations`             | `false` | Also return annotations for both sides.                                               |
| `minMoveWords`            | `4`     | Shortest run of words that can be reported as moved.                                  |
| `pageSimilarityThreshold` | `0.4`   | How similar two pages must be to be compared word by word.                            |
| `colors`                  |         | `{ inserted, deleted, moved }` colours for the annotations.                           |
| `author`                  |         | Author written on the annotations.                                                    |

Differences in the amount of white space and in line breaks are never reported, because words are compared, not characters.

## The compare view

`viewer.compareWith(other, { fileName })` compares the open document, including unsaved changes, with another file and opens the result in a full-size dialog. **Compare documents** in the menu does the same after the user picks a file. The open document is side A and the other file is side B.

```ts
const previous = await fetch('/contracts/services-agreement-fabrikam-2026-draft-3.pdf');
await viewer.compareWith(await previous.arrayBuffer(), { fileName: 'draft-3.pdf' });
```

The promise resolves when the dialog is closed. The view has:

- Two panes that render both documents page by page, aligned by the page comparison, with deletions marked on the left, insertions on the right and moved text on both.
- **Side by side** and **Overlay** buttons, and **Scroll together**, which is on by default.
- The number of differences, **Previous difference** and **Next difference** buttons, and a list of all differences with their type, page and text. Selecting one scrolls both panes to it. N or the right arrow and P or the left arrow step through them.
- **Text** and **Visual** buttons, which switch between the word comparison and the [visual comparison](#visual-comparison).

The compare view uses the default options of `comparePdf` and is read-only: it does not add annotations to the open document. To keep the result, call `comparePdf` with `annotations: true` yourself, as shown below.

### Exporting a report

**Export report** in the compare view downloads the list of changes as an HTML page or as CSV, and the viewer emits `compareReport` with `{ format, report, summary }`. `buildCompareReport(comparison, options)` builds the same report from a comparison without a viewer.

```ts
import { buildCompareReport, comparePdf, openPdfDocument } from '@birchui/pdf/engine';

declare const first: Uint8Array;
declare const second: Uint8Array;
const comparison = comparePdf(openPdfDocument(first), openPdfDocument(second));

const html = buildCompareReport(comparison, { fileNameA: 'msa-v1.pdf', fileNameB: 'msa-v2.pdf' });
const csv = buildCompareReport(comparison, { format: 'csv' });
const data = JSON.parse(buildCompareReport(comparison, { format: 'json' })) as { changes: unknown[] };
console.info(html.length, csv.split('\r\n').length, data.changes.length);
```

`format` is `'html'` (the default), `'csv'` or `'json'`. The report holds the names of the two files, the date, the counts of unchanged, changed, added, removed and moved pages, the word counts, and one row per change with its type, its page in each document and its text. `labels` replaces the English words of the report. Text is escaped for HTML, and a CSV cell that begins with `=`, `+`, `-` or `@` is prefixed so a spreadsheet does not run it as a formula. The report lists text changes; the regions of the [visual comparison](#visual-comparison) are not part of it.

## Visual comparison

**Visual** in the compare view compares what the two documents look like instead of what they say. Each pair of aligned pages is rendered at the same fixed scale (1.5 pixels per point, less for very large pages), the two images are compared pixel by pixel, and every pixel that differs by more than the tolerance is painted on both panes in a highlight colour that is stronger where the difference is larger. This finds what the text comparison cannot: a replaced image, a moved line, a changed colour or font, a stamp or a drawing.

```ts
const draft = await fetch('/contracts/services-agreement-fabrikam-2026-draft-3.pdf');
await viewer.compareWith(await draft.arrayBuffer(), { fileName: 'draft-3.pdf', view: 'visual' });
```

`view: 'visual'` opens the view in this mode; the default is `'text'`. In visual mode the view has:

- **Difference opacity**, a slider from 0 to 100 percent for the highlight layer, so the page under it can be read.
- A list of **changed areas** in place of the list of text differences. Neighbouring changed pixels are grouped into one area; each entry names the page and the share of the page that differs, and selecting it scrolls both panes to the area and outlines it. The list is reached with Tab, entries are buttons, and N, P, the arrow keys and the **Previous difference** and **Next difference** buttons step through the areas as they do through text differences.
- Pages that exist in only one document, listed as such.

Pages are compared when they come near the visible part of the panes, one pair at a time. A comparison is cancelled when its pages are scrolled away before it finishes, the highlight layer of a page far from view is released and built again when the page returns, and the status next to the buttons says how many pages have been compared so far. Everything is released when the view closes.

The comparison itself is a pure function you can use on any two RGBA buffers, for example canvases you rendered yourself:

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

function highlightDifferences(before: HTMLCanvasElement, after: HTMLCanvasElement, overlay: HTMLCanvasElement) {
  const read = (canvas: HTMLCanvasElement) => canvas.getContext('2d')?.getImageData(0, 0, canvas.width, canvas.height);
  const imageA = read(before);
  const imageB = read(after);
  if (!imageA || !imageB) return [];
  const result = diffPixels(imageA, imageB, { tolerance: 16, mergeDistance: 12 });
  overlay.width = result.width;
  overlay.height = result.height;
  overlay.getContext('2d')?.putImageData(new ImageData(result.mask, result.width, result.height), 0, 0);
  console.info(`${result.changedPixels} pixels differ, ${(result.changedRatio * 100).toFixed(2)}% of the page`);
  return result.regions;
}
```

| `PixelDiffOptions` | Default                | Meaning                                                                                                   |
| ------------------ | ---------------------- | --------------------------------------------------------------------------------------------------------- |
| `tolerance`        | `16`                   | Largest difference of a colour or alpha channel, 0 to 255, that still counts as equal                     |
| `color`            | `[214, 0, 110]`        | RGB of the highlight in `mask`; its alpha runs from 110 at the tolerance to 255 at the largest difference |
| `padding`          | `[255, 255, 255, 255]` | RGBA assumed outside the smaller image when the sizes differ                                              |
| `mergeDistance`    | `0`                    | Changed pixels closer than this many pixels are put in the same area                                      |
| `cellSize`         | `8`                    | Size in pixels of the grid used to group pixels into areas                                                |
| `minRegionPixels`  | `1`                    | Areas with fewer changed pixels are left out of `regions` (they stay in `mask` and `changedPixels`)       |
| `maxRegions`       | `200`                  | The largest areas are kept when there are more                                                            |

The result has the size of the larger image in each direction. `regions` are bounding boxes in pixels from the top left corner, ordered from the top of the page.

## Showing the result in your own layout

With `annotations: true` the result has `annotations.a` and `annotations.b`: strikeouts for deletions on A, highlights for insertions on B and highlights in a third colour for moved text on both sides. They are ordinary annotation inputs, so two viewers side by side can show them directly:

```ts
declare const leftPane: HTMLElement;
declare const rightPane: HTMLElement;
declare const result: import('@birchui/pdf').PdfComparison;

const left = createPdfViewer(leftPane, { document: draft, readOnly: true });
const right = createPdfViewer(rightPane, { document: signed, readOnly: true });
await Promise.all([left.ready, right.ready]);

if (result.annotations) {
  left.addAnnotations(result.annotations.a);
  right.addAnnotations(result.annotations.b);
}
```

For an overlay on the newer file alone, add `annotations.b` and list the deletions from `result.changes` in your own panel. Each annotation carries `customData.compare` with the change type, which makes them easy to filter or remove again.

`comparisonAnnotations(changes, { colors, author })` builds the same annotations later from a stored list of changes.

## Password-protected files

`comparePdfAsync(a, b, options)` takes the same options as `comparePdf` plus `password` for the first file and `otherPassword` for the second. Either the user or the owner password works. A missing or wrong password rejects with `PdfPasswordError` (`reason` is `password-required` or `password-incorrect`).

```ts
import { comparePdfAsync, loadPdfDocument } from '@birchui/pdf/engine';

const result = await comparePdfAsync(draft, signed, {
  password: 'draft-2026',
  otherPassword: 'signed-2026',
  annotations: true,
});
console.info(result.summary.wordsInserted, result.summary.wordsDeleted);

const open = await loadPdfDocument(draft, { password: 'draft-2026' });
const again = await open.compareWith(signed, { password: 'signed-2026', ignoreCase: true });
console.info(again.summary.isIdentical);
```

Both functions, and `comparePdf`, also accept documents that are already open instead of bytes: a `PdfDocument` from `openPdfDocument` or `loadPdfDocument`, or anything with `pageCount` and `getPageText(pageIndex)`. An open document is compared as it is now, with unsaved content edits and without the text under applied redactions. `document.compareWith(other, options)` compares the open document (side A) with bytes or another document (side B); its `password` option opens the other file.

## Comparing text you already have

`comparePageTexts(pagesA, pagesB, options)` takes arrays of `{ text, boxes }`, one per page, and returns the same result. Use it when the text comes from somewhere else, for example OCR. Without boxes the changes have empty `rects`.

## Visual comparison without a browser

`comparePdfVisual` from `@birchui/pdf/render` runs the text comparison and then renders every aligned pair of pages with the package's own engine and compares the pixels. It needs no canvas, so it runs in Node and in a worker.

```ts
import { readFile } from 'node:fs/promises';
import { comparePdfVisual } from '@birchui/pdf/render';
import { createStandardFontProvider } from '@birchui/pdf/render-fonts';

const result = await comparePdfVisual(await readFile('msa-v3.pdf'), await readFile('msa-v4.pdf'), {
  standardFonts: async () => createStandardFontProvider(),
});
for (const page of result.visual) {
  if (page.status !== 'changed') continue;
  console.info(`page ${(page.pageIndexB ?? 0) + 1}: ${page.regions.length} changed areas`);
}
```

The result is the `PdfComparison` of `comparePdfAsync` plus `visual`, one entry per row of `pages`: `status` is `'equal'`, `'changed'`, or `'only-a'` / `'only-b'` for a page without a partner (not rendered), and `regions` lists every changed area with its pixel box and a `rect` in points measured from the top left of the page. Options: `scale` (pixels per point, default 1.5), `tolerance` (0 to 255, default 16), `mergeDistance` (pixels, default 12), `maxPixels` (default 4,000,000; a larger page is compared at a lower scale, reported as `scale`), `standardFonts` for fonts that are not embedded, and the options of `comparePdfAsync`. Both inputs must be bytes. It lives in the render entry because it needs the rendering engine; `comparePdf` in `@birchui/pdf/engine` stays small.

## Limits

- `comparePdf` is about text. Images, vector art, annotations and form values are not compared by it; the [visual comparison](#visual-comparison) of the compare view shows those as changed areas, without saying what changed.
- Scanned pages without a text layer all look empty and are reported as unchanged.
- Text is read in content-stream order. A file whose producer writes columns or tables out of reading order can show more moved or changed text than a person would expect.
- A moved block is only recognized when its words are identical in both places.
- Very large pages (several thousand changed words on one page) fall back to a coarser diff that stays fast and may report one larger change instead of several small ones.
- `comparePdf` is not pixel-based: two pages that look different but hold the same words are reported as unchanged. Use [`comparePdfVisual`](#visual-comparison-without-a-browser) or the visual mode of the compare view for those.
- The visual comparison compares pages in the pairs the text comparison aligned. A paragraph that moves down by a line makes everything after it differ, and it does not follow text across a page break. It is computed on the main thread, one page pair at a time: the pages near the viewport first, then every other page in the background, so the list of changed areas fills in to the end without scrolling and the count shows the progress until it is complete. The coloured layer is kept only for the pages near the viewport. Its tolerance, scale and colour are fixed in the view.
- `comparePdf` itself cannot unlock a file, because decryption is asynchronous: it throws `PdfPasswordError` for locked bytes. Use `comparePdfAsync` or pass open documents, as described under [Password-protected files](#password-protected-files).
- The compare view of the viewer cannot be used while the open document is encrypted.
