# Redaction

> Mark text, patterns and areas for redaction, review the marks, apply them and save a rewritten file from which the text, image pixels and vector art are really removed, with a precise list of what is and is not removed.

Redaction in Birch UI PDF has two steps on purpose. **Marks** are ordinary annotations: they can be reviewed, moved and deleted, and nothing is removed while they exist. **Applying** them schedules the covered content for removal, and the next save writes a new file without it.

```ts
viewer.markRedactions({ preset: 'iban' });
viewer.markRedactions({ text: 'Fabrikam Logistics GmbH', wholeWord: true }, { overlayText: 'Counterparty' });
viewer.markRedactions({ pattern: /Customer no\.\s*\d{6}/g }, { fillColor: '#1f2328' });
viewer.addAnnotation({ type: 'redaction', pageIndex: 2, rect: [72, 300, 300, 350] });

const applied = viewer.applyRedactions();
const { bytes, mode, redactions } = await viewer.save();

console.info(applied, mode, redactions.map((report) => report.removedText));
```

## Marking

| Way | How |
| --- | --- |
| Redact tool (X) | Select text, or drag over an area such as a photo or a signature |
| Context menu | Select text with the Select tool, right-click, **Redact** |
| Redaction panel | **Search and redact**: type a text or choose a pattern, optionally an overlay text, then **Mark matches** |
| `markRedactions(query, options)` | A text, a regular expression or a preset; see the table below |
| `addAnnotation({ type: 'redaction', … })` | A `rect`, or `quadPoints` for several lines |

The query says what kind of search you mean, so a word is never mistaken for a preset:

| `RedactionQuery` | Finds |
| --- | --- |
| `{ text, matchCase?, wholeWord? }` | The literal text. Case is ignored unless `matchCase` is set. |
| `{ pattern }` | Every match of the regular expression |
| `{ preset }` | One of the built-in patterns, by name |
| `'some text'` | Shorthand for `{ text: 'some text' }`. A string is always literal text, also when it equals a preset name. |
| `/expression/` | Shorthand for `{ pattern: /expression/ }` |

The built-in patterns are in `REDACTION_PATTERNS`, their names in `REDACTION_PATTERN_NAMES` and the type `RedactionPatternName`: `email`, `phone`, `ssn`, `creditCard`, `iban` and `date`. They are deliberately broad regular expressions, not validators: `creditCard` matches any run of 13 to 16 digits, and `date` only numeric dates such as `03/03/2026`. Review what they mark.

```ts
import { REDACTION_PATTERN_NAMES, type RedactionPatternName } from '@birchui/pdf';

const chosen: RedactionPatternName[] = REDACTION_PATTERN_NAMES.filter((name) => name !== 'date');
for (const preset of chosen) viewer.markRedactions({ preset }, { pages: [0, 1] });
```

| `RedactionSearchOptions` | Meaning |
| --- | --- |
| `pages` | Zero-based page indexes to search; all pages by default |
| `caseSensitive`, `wholeWord` | For text queries that do not set `matchCase` or `wholeWord` themselves |
| `overlayText` | Text drawn on the redacted area, for example an exemption code |
| `fillColor` | Fill of the redacted area; black by default |

> **Note**
>
> Before this version a string that equalled a preset name, such as `'email'`, selected the preset. It now marks the word itself. Change such calls to `{ preset: 'email' }`. An unknown preset name marks nothing and logs one warning.

Text is found with the package's own text extraction, the same one the headless `findText` and `extractText` use. A match that wraps over two lines gets one mark with two rectangles.

## Reviewing

The Redaction panel lists every mark with its page and the text it covers; clicking an entry scrolls to it, and the button next to it removes the mark. On the page, a mark is an outlined box that you can select, move, resize and delete like any annotation. The style bar changes its fill colour, and `overlayText` and `fillColor` can be changed with `updateAnnotation`.

Marks are saved as `/Redact` annotations when you save without applying them, so a second person can review them later in Birch UI PDF or in Acrobat.

## Applying

**Apply all** in the Redact tool group or in the Redaction panel shows a confirmation and then applies every mark. `applyRedactions(ids?)` applies all marks or the given ones and returns how many were applied; it does not ask.

After applying:

- The marks are gone and the areas are drawn filled. Annotations and form widgets that intersect an area are removed with them.
- Search, `getPageText()` and text selection on those pages no longer return the covered text.
- The step can be undone until you save. `canUndo()` and the undo button work as for any other change.

> **Warning**
>
> The **Apply redactions** button inside the popover of a single mark applies that mark immediately, without the confirmation dialog.

## Saving

A document with applied redactions is always saved as a [full rewrite](https://docs.birchui.com/pdf/saving.md#full-rewrites), so the removed content does not survive in an earlier revision of the file. For every page with redactions:

- **Text** is removed glyph by glyph. A partly covered line is rewritten with spacing adjustments, so the remaining words keep their exact positions.
- **Images** that lie completely inside an area are removed. For an image that is partly covered, only the pixels inside the area are painted with the fill colour; its soft mask or stencil mask is made opaque there. The image is written back losslessly (Flate), in its own colour space, and the original image data is not in the saved file. See [Images under a redaction](#images-under-a-redaction) for which images can be kept.
- **Inline images** that touch an area are removed.
- **Vector paths and shadings** that lie completely inside an area are dropped; partly covered ones remain under the filled box.
- **Form XObjects** that touch an area are rewritten by the same rules, up to three levels deep. A form nested deeper than that is removed.
- **Annotations and form widgets** that intersect an area are deleted.
- The area is painted with the fill colour and the optional overlay text.

- The page thumbnail and private application data of the page (`/Thumb`, `/PieceInfo`) are dropped, because they can hold a copy of the unredacted page.

`SaveResult.redactions` has one report per redacted page with `glyphsRemoved`, `removedText`, `imagesRemoved`, `imagesModified`, `pathsRemoved`, `formsRewritten` and `images`. Keep it out of logs that the recipients of the redacted file can read: `removedText` is exactly the text that was removed.

## Images under a redaction

A scanned page is one large picture, so what happens to a partly covered image decides whether the rest of the scan survives.

| Image | What happens |
| --- | --- |
| Flate, LZW, run-length or uncompressed samples; grey, RGB, CMYK, ICC-based, calibrated or palette colours; 1, 2, 4, 8 or 16 bits; stencil masks | Painted in place, in the same format |
| JPEG (`DCTDecode`): baseline and progressive, 8 bits, grey, YCbCr, RGB, CMYK and YCCK, any chroma subsampling, restart intervals | Decoded by the package, painted and written as a baseline JPEG in the same colour space. Blocks a mark does not touch keep their original coefficients; the others are compressed with the quantization tables of the source |
| JPEG 2000, JBIG2, CCITT fax, arithmetic-coded or 12-bit JPEG, Lab, Separation and DeviceN colours | Painted when a `decodeImage` callback returns the pixels; otherwise the whole image is removed |
| Inline images | Removed |

The package has no decoder for JPEG 2000, JBIG2 and CCITT. Supply one with `decodeImage` on the headless document. The callback gets the encoded data and what is known about the image, and returns RGBA pixels or `undefined`:

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

async function decodeImage(image: PageRedactionImage): Promise<DecodedRedactionImage | undefined> {
  if (image.filter !== 'JPXDecode') return undefined;
  const bitmap = await createImageBitmap(new Blob([image.data.slice()], { type: 'image/jp2' }));
  const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
  const context = canvas.getContext('2d');
  if (!context) return undefined;
  context.drawImage(bitmap, 0, 0);
  return { width: bitmap.width, height: bitmap.height, rgba: context.getImageData(0, 0, bitmap.width, bitmap.height).data };
}

const pdf = openPdfDocument(bytes);
pdf.markRedactions({ preset: 'iban' });
const waiting = pdf.getRedactionImages();
console.info(waiting.map((image) => [image.pageIndex, image.filter, image.width, image.height]));

await pdf.applyRedactionsAsync(undefined, { decodeImage });
const { redactions } = await pdf.save();
for (const report of redactions) {
  for (const image of report.images) {
    if (image.action === 'removed') console.warn(image.name, image.reason, image.message);
  }
}
```

- `applyRedactions(ids?, { decodeImage })` takes a synchronous callback; `applyRedactionsAsync(ids?, { decodeImage })` takes one that may return a promise. Both return the number of applied marks.
- `getRedactionImages(ids?)` lists the images that the given marks (all marks by default) touch and that the package cannot decode itself, so that you can warn the user or decode ahead of time. It is empty when nothing needs a callback.
- `PageRedactionImage` has `data` (the bytes the image filter applies to), `filter`, `width`, `height`, `bitsPerComponent`, `colorSpace`, `isMask`, `decode`, `decodeParms` (for example `K`, `Columns` and `BlackIs1` of a fax image), `jbig2Globals`, and where the image is: `pageIndex`, `rect`, `matrix`, `name` and `role` (`image`, `softMask` or `mask`). A callback that cannot decode the data can instead rasterise that part of the page.
- The returned raster replaces the image: as RGB, as grey when all pixels are grey, or as 1-bit when they are only black and white. Transparency in the raster becomes a soft mask. For a stencil mask (`isMask`), transparent pixels, or light pixels of a fully opaque raster, are the unpainted ones. The raster may have a different size than the original; the placement on the page stays the same.
- The callback is asked once per image, when the marks are applied. A callback that throws, rejects or returns an invalid raster counts as "no pixels".
- Each entry of `report.images` has the `name`, the `action` (`modified` or `removed`), the `filter`, `decodedBy` (`package` or `callback`) or, for a removed image, the `reason` (`covered`, `undecodable`, `mask-undecodable` or `inline-image`) and a `message`.

`decodeJpeg(bytes)` is exported for the same decoder that the package uses: it returns `{ width, height, components, data }` with 1, 3 or 4 samples per pixel and throws `JpegError` for data it does not support.

The same works without a viewer:

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

const pdf = openPdfDocument(await readFile('disclosure/invoice-2026-0311.pdf'));
pdf.markRedactions({ preset: 'email' });
pdf.markRedactions({ preset: 'iban' });
pdf.applyRedactions();
const saved = await pdf.save();
await writeFile('disclosure/invoice-2026-0311-redacted.pdf', saved.bytes);
```

## What redaction does not do

- **It does not find text it cannot read.** Scanned pages have no text, and there is no OCR. Mark such content by dragging an area. Text in a font without a usable Unicode mapping is not found by search either, although an area mark still removes its glyphs.
- **Scans in JPEG 2000, JBIG2 or CCITT format need a decoder from you.** Without a `decodeImage` callback, an image in one of these formats is removed as a whole when a mark touches it, and the report says so. The viewer's own **Apply** commands do not pass a callback. JPEG scans are handled by the package.
- **A redacted JPEG stays a JPEG of about the same size.** Blocks outside the marks are copied bit for bit in value; the 8 or 16 pixel blocks a mark touches are compressed again, so pixels next to the edge of a mark can change by a few levels. A progressive file becomes a baseline file. An arithmetic-coded or 12-bit JPEG that a `decodeImage` callback decoded is written as a baseline JPEG with the tables of the source.
- **Rotated or skewed images are painted over the bounding box** of the area in image space, which can cover slightly more of the picture than the mark shows.
- **Only page content is redacted.** Document properties, XMP metadata, bookmark titles, attachments, the values of form fields elsewhere and comments on annotations outside the areas are not searched or changed. Run [Sanitize](https://docs.birchui.com/pdf/document-tools.md#sanitize) after applying the redactions to remove document properties, XMP, attachments, scripts, comments and hidden layers; its page lists [what it removes](https://docs.birchui.com/pdf/document-tools.md#what-is-removed) and [what it leaves](https://docs.birchui.com/pdf/document-tools.md#what-is-not-removed), which includes bookmark titles and form field values. `getMetadata()`, `getOutline()` and `getAttachments()` read them.
- **Text converted to outlines is vector art** and follows the rule for paths: it is removed only when it lies completely inside the area.
- **Hidden layers** (optional content) are treated like visible content; content outside the crop box is redacted only if a mark covers it.
- **Existing digital signatures become invalid**, because the file is rewritten.

Open the saved file and search for a few of the removed strings before you send it out. The check is cheap and it is your proof that the file you send is the redacted one.
