# Content editing

> Replace, move and delete text runs, move, resize, replace and delete placed images, add new text and images, read the page text in reading order and get snap geometry with the headless API, with an honest list of what PDF content editing cannot do.

Annotations sit on top of a page. Content editing changes the page itself: the text and images inside the content stream. Birch UI PDF supports a deliberately narrow version of it, in the headless API: text is edited and moved run by run, placed images can be moved, resized, replaced and deleted, and new text and images can be added.

A PDF page is not a document with paragraphs. It is a list of drawing instructions, each placing a few glyphs at fixed coordinates. Read the [limits](#limits) before you build a feature on top of this.

## Finding text

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

const pdf = openPdfDocument(await readFile('delivery-note-48213.pdf'));
const runs = pdf.getTextRuns(0);
```

A run is one text-showing instruction in the content stream. It has the `text`, the bounding `rect`, the `origin` of its baseline, the `fontName` it uses in the page resources, the `baseFont`, the `fontSize`, its `advance` width and its `index`. Most producers write a line or a part of a line per run; some write a run per word.

## Replacing and deleting text

```ts
const run = pdf.getTextRuns(0).find((r) => r.text === 'Pallets shipped: 48');
if (run) {
  const result = pdf.editPageText(0, run, 'Pallets shipped: 52');
  if (!result.ok) console.warn(result.reason, result.message);
}
```

The result tells you what happened:

- `ok: true, usedFont: 'original'`: the run's own font had every glyph, so only the string changed.
- `ok: true, usedFont: 'embedded'`: the font lacked a glyph and a font you supplied when opening the document was embedded for this run. See [Fonts](https://docs.birchui.com/pdf/fonts.md).
- `ok: false, reason: 'missing-glyphs'`: the font lacks the characters in `missing` and no supplied font covers them. Nothing was changed.
- `ok: false, reason: 'unsupported-font'`: the font cannot be written to (see the limits), and no supplied font covers the text.
- `ok: false, reason: 'stale-hit'`: the page changed since you fetched the run. Call `getTextRuns` again; run indexes shift after an edit.
- `ok: false, reason: 'empty-text'`: the new text is empty. Use `deletePageText(pageIndex, run)` to remove a run.

`fontNames` lists the fonts that were used and `widthChange` the difference in width, in points. Text that follows the edited run on the same line keeps its position: the difference in width is compensated inside the content stream. Nothing else on the page moves.

## Editing a paragraph

`getTextParagraphs(pageIndex)` groups the runs of a page into paragraphs, and `editPageParagraph` replaces the text of one and breaks it into lines again inside the block:

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

declare const agreementBytes: Uint8Array;

const agreement = openPdfDocument(agreementBytes);
const paragraph = agreement.getTextParagraphs(0).find((item) => item.text.startsWith('Client will pay'));
if (paragraph) {
  const result = agreement.editPageParagraph(
    0,
    paragraph,
    'Client will pay the fees set out in Schedule A within forty-five (45) days of the invoice date.',
  );
  console.info(result.ok, result.lines, result.overflow, result.usedFont);
}
```

A paragraph is a set of consecutive lines of upright, horizontal text that share one font, size and scale, start at the same left edge and are the same distance apart. Runs on one baseline that are further apart than two and a half times the font size are different columns. Rotated text and lines that mix fonts or sizes are not part of any paragraph; edit those run by run. Each `TextParagraph` has `text` (the lines joined with spaces), `lines`, `runs`, `rect`, `fontName`, `fontSize` and `lineHeight`.

`editPageParagraph` keeps the font, the size, the fill colour, character and word spacing, the left edge, the first baseline and the line distance. It also keeps the alignment (`paragraph.alignment`): a right-aligned or centred paragraph is wrapped again around the same edge or axis, and in a justified paragraph every line but the last is stretched to the block width by widening the spaces, as before the edit. The new text is wrapped at spaces to the width of the original block (the right edge of its longest line), or to `options.width` in points; a line break in the text starts a new line, and a word that is wider than the block is broken. The result reports the `lines` as written, their `rect`, and `overflow`: how far, in points, the last baseline lies below the last baseline of the original block. Characters the original font cannot draw are drawn with the fonts of the document's `fonts` option, shaped as described under [Fonts](https://docs.birchui.com/pdf/fonts.md); the result then has `usedFont: 'embedded'`, and without a font that covers them the edit is refused with `missing-glyphs` and nothing changes. The edit is one undo step.

## Moving text

```ts
const total = pdf.getTextRuns(0).find((r) => r.text.startsWith('Total due'));
if (total) {
  const moved = pdf.movePageText(0, total, { dx: 0, dy: -14 });
  if (moved.ok && moved.run) console.info(moved.run.origin);
}
```

`movePageText(pageIndex, run, { dx, dy })` translates one run by an offset in PDF user space (points on an unscaled page), also when the run sits inside a scaled or rotated coordinate system. Only that run moves: the text that follows it in the same text object stays where it was. The result has the run at its new place in `run`, ready for the next call, because run indexes change with every edit.

## Images on a page

```ts
declare function readFile(path: string): Promise<Uint8Array>;

const images = pdf.getPageImages(0);
for (const image of images) console.info(image.id, image.rect, image.width, image.height, image.format);

const logo = images.find((image) => image.format === 'jpeg');
if (logo) {
  const moved = pdf.movePageImage(0, logo, { dx: 24, dy: 0 });
  const resized = pdf.movePageImage(0, moved.image ?? logo, { rect: [72, 680, 192, 740] });
  const swapped = pdf.replacePageImage(0, resized.image ?? logo, await readFile('logo-2026.png'));
  if (swapped.image) pdf.deletePageImage(0, swapped.image);
}
```

`getPageImages(pageIndex)` lists every image drawn by the page's own content stream, in drawing order:

| `PageImage` | Meaning |
| --- | --- |
| `id` | Identifies the placement until the next edit of the page |
| `rect` | Bounding rectangle in PDF user space |
| `quad` | The four corners (bottom left, bottom right, top right, top left of the image), for rotated placements |
| `matrix` | The placement matrix that maps the unit square to the page |
| `width`, `height` | Size in pixels |
| `format` | `raw`, `jpeg`, `jpeg2000`, `jbig2`, `ccitt` or `unknown` |
| `filter`, `bitsPerComponent`, `colorSpace`, `isMask`, `hasAlpha` | Details of the image data |
| `name`, `ref`, `index` | The resource name, the object and the position in the content stream |

- `movePageImage(pageIndex, image, move)` changes the placement. An image that sits inside a clip path of its own, as every image in a LibreOffice export does, takes the clip with it, so it is not cut off at its old position and a crop stays a crop. When the clipped group also draws other things, the image is drawn after that group instead, without the clip. `move` is `{ dx, dy }` to translate, `{ rect }` to move and scale the bounding rectangle to a new one (a rotated image keeps its rotation), or `{ matrix }` to set the placement matrix directly.
- `replacePageImage(pageIndex, image, data)` puts a PNG or JPEG (or the result of `prepareImage`) in the same place. The new picture is stretched to the old placement, so keep the aspect ratio or resize afterwards.
- `deletePageImage(pageIndex, image)` removes the drawing instruction. When nothing else on the page uses the image, it is also taken out of the page resources, so a full rewrite (`save({ mode: 'full' })`) no longer contains its data. An incremental save keeps the old bytes in the earlier revision.
- `image` is a `PageImage` or its `id`. Every result has `ok`, and on success the `image` as it is now. `reason` is `stale-hit` when the page changed since `getPageImages`, `not-invertible` for a matrix without area and `unsupported-image` for data that is neither PNG nor JPEG.

## Adding text and images

```ts
declare function readFile(path: string): Promise<Uint8Array>;

const stamp = pdf.addPageText(0, {
  text: 'Checked at gate 4\n12 March 2026',
  x: 72,
  y: 120,
  fontSize: 11,
  color: '#1a4d8f',
  font: 'Helvetica-Bold',
});
if (stamp.ok) console.info(stamp.rect);

pdf.addPageImage(0, {
  data: await readFile('stamp-received.png'),
  rect: [400, 80, 540, 150],
  opacity: 0.85,
  rotation: 8,
});
```

- `x` and `y` are the start of the first baseline in PDF user space. `rotation` is in degrees, counter-clockwise, around that point for text and around the centre of the rectangle for images. Lines are split at line breaks and spaced by `lineHeight` (default 1.2). `fontSize` defaults to 12.
- `font` is one of the twelve standard Helvetica, Times and Courier faces. They cover Western European text; the result then has `usedFont: 'standard'`. For anything else, supply fonts when you open the document; the right one is embedded as a subset. Without a font that covers the text, the result is `ok: false` with `reason: 'missing-glyphs'`.
- `data` is a PNG or a JPEG. Other formats are converted with `prepareImage` first; see [Image formats](#image-formats). Data that is neither gives `reason: 'unsupported-image'`.
- New content is drawn after the existing content, inside its own graphics state, so leftover clipping or transformations from the page cannot affect it.

Each successful edit is one undo step, emits `pagesChange` with the reason `content` and `documentChange`, is saved with the next `save()` and can be written as an incremental update. A failed edit leaves the document untouched.

## Image formats

Page images (`addPageImage`, `replacePageImage`), image and stamp annotations (`image` on an annotation), image signatures and `imagesToPdf` all take the same formats through one path, `prepareImage`. The format is recognised from the first bytes of the file, never from its name.

| Format | Page content | Stamp or image annotation | `imagesToPdf` | How it is read |
| --- | --- | --- | --- | --- |
| PNG | yes | yes | yes | By the package. Greyscale, RGB and palette, 1 to 16 bits, alpha channel, `tRNS` transparency, interlaced or not. |
| JPEG | yes | yes | yes | Stored as it is (`/DCTDecode`), baseline or progressive, greyscale, RGB or CMYK. Not decoded. |
| GIF | yes | yes | yes | By the package: the first frame of GIF87a and GIF89a, interlaced or not, with its transparent colour. |
| BMP | yes | yes | yes | By the package: 1, 4, 8, 16, 24 and 32 bits, bottom-up and top-down, bit masks (also with alpha), RLE4 and RLE8. |
| TIFF | yes | yes | yes | By the package: the first image of a strip-based file, uncompressed, PackBits, LZW or Deflate, 1 to 16 bits, greyscale, RGB or palette, with an alpha sample. |
| WebP, SVG, AVIF and others | with `decodeImage` | with `decodeImage` | with `decodeImage` | By your callback. The viewer has a default that uses the browser. |

```ts
declare const logoGifBytes: Uint8Array;

const image = await pdf.prepareImage(logoGifBytes);
pdf.addPageImage(0, { data: image.data, rect: [72, 600, 72 + image.width / 2, 600 + image.height / 2] });
pdf.addAnnotation({ type: 'stamp', pageIndex: 0, rect: [300, 600, 380, 660], image });
```

`prepareImage(bytes, options?)` resolves to `{ data, mimeType, width, height }`, where `data` is a PNG or a JPEG. PNG and JPEG input is returned unchanged; every other format is decoded to RGBA and encoded as a PNG, so what is stored in the PDF is lossless and keeps its transparency as a soft mask. It is a method of the document and of the viewer, and a function exported from `@birchui/pdf/engine`.

What ends up in the file:

- A palette PNG becomes an `/Indexed` image with its palette, a 16-bit PNG keeps 16 bits per component, and everything else is 8-bit `/DeviceGray` or `/DeviceRGB`. Alpha, of any source depth, is an 8-bit `/SMask`.
- A CMYK JPEG is written as `/DeviceCMYK` with an inverting `/Decode` array, which is what Adobe-style CMYK JPEG data needs.
- GIF, BMP, TIFF and callback results are stored as RGB or RGBA PNG data, whatever the source colour model was.

### Formats that need a decoder

The package does not contain a WebP or SVG decoder. In the browser the viewer decodes them with an `<img>` element and a canvas: raster formats at their own size (scaled down above 16 megapixels), SVG at a scale that makes its longer side 2048 pixels, because a vector drawing has no pixel size of its own. Pass `decodeImage` to replace that, for instance to rasterise SVG at another size.

The headless engine has no default. Without a callback, `prepareImage` rejects with an `ImageDecoderRequiredError` that names the media type:

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

declare function rasterise(file: Uint8Array, type: string): Promise<{ width: number; height: number; rgba: Uint8Array }>;
declare const signWebpBytes: Uint8Array;

const decodeImage: ImageDecoder = async (file, mimeType) => {
  const raster = await rasterise(file, mimeType);
  return { width: raster.width, height: raster.height, data: raster.rgba };
};

const report = openPdfDocument(draft, { decodeImage });
try {
  const sign = await report.prepareImage(signWebpBytes);
  report.addPageImage(0, { data: sign.data, rect: [72, 72, 172, 172] });
} catch (error) {
  if (error instanceof ImageDecoderRequiredError) console.warn(`No decoder for ${error.mimeType}`);
  else throw error;
}
```

The callback gets the bytes and the detected media type (`image/webp`, `image/svg+xml`, or the type you passed as `mimeType` for a format the package does not recognise) and returns `{ width, height, data }` with `width × height × 4` bytes of non-premultiplied RGBA, or `undefined` when it cannot read the file. It may return a promise. Set it once when opening the document or creating the viewer, or per call in the options of `prepareImage` and `imagesToPdf`. It is also asked when the package's own GIF, BMP or TIFF decoder rejects a file.

Every failure is an `ImageFormatError`: a file that is not an image, truncated data, a variant the decoder does not cover, a callback that returns nothing, and dimensions above 65,535 pixels on a side or 100 million pixels in total.

## Extracting images

`extractImages(pageIndex)` returns the images the page's content stream draws, in drawing order, with their pixels:

```ts
for (const image of pdf.extractImages(0)) {
  if (image.status === 'decoded' && image.data) {
    console.info(image.name, image.data.width, image.data.height, image.data.rgba.length);
  } else if (image.status === 'encoded-only' && image.encoded) {
    console.info(image.name, image.encoded.mimeType, image.encoded.filter, image.encoded.bytes.length);
  } else console.warn(image.name, image.message);
}
```

| `ExtractedImage` | Meaning |
| --- | --- |
| `name`, `index`, `id`, `ref` | Resource name, position of the drawing operator, both joined as an id, and the object reference. Inline images are named `inline-1`, `inline-2`, … and have no `ref`. |
| `isInline` | `true` for an image written inside the content stream (`BI … EI`) |
| `rect`, `quad`, `matrix` | Where it is drawn, as for `getPageImages` |
| `width`, `height`, `bitsPerComponent`, `colorSpace`, `filters` | The image dictionary: size in pixels, sample depth, colour space family and the filter chain |
| `format` | `raw`, `jpeg`, `jpeg2000`, `jbig2`, `ccitt` or `unknown` |
| `isMask`, `hasMask` | A 1-bit stencil; an image with a soft mask, a stencil mask or a colour key |
| `status` | `decoded`, `encoded-only` or `unsupported` |
| `data` | `{ width, height, rgba }`, non-premultiplied RGBA, when `status` is `decoded` |
| `encoded` | `{ mimeType, filter, bytes, decodeParms?, jbig2Globals? }` for JPEG, JPEG 2000, JBIG2 and CCITT data |
| `isRendered`, `message` | Set by the viewer's render fallback; a sentence that says why an image was not decoded |

| `status` | When | What you get |
| --- | --- | --- |
| `decoded` | Uncompressed, Flate, LZW, ASCII85, ASCIIHex and RunLength data with PNG or TIFF predictors, and baseline or progressive JPEG | `data`; for JPEG also `encoded` with the original JPEG bytes |
| `encoded-only` | JPEG 2000 (`image/jp2`), JBIG2 (`image/x-jbig2`), CCITT fax (`image/g3fax`), and a JPEG the package cannot decode | `encoded`, the bytes as they are stored after any outer text or Flate filters were removed |
| `unsupported` | A colour space the package does not convert (Lab, Separation, DeviceN, Pattern) or damaged data | Neither; `message` says why |

Decoding covers 1, 2, 4, 8 and 16 bits per component in DeviceGray, DeviceRGB, DeviceCMYK, CalGray, CalRGB, Indexed and ICCBased colour spaces (an ICC profile is treated as grey, RGB or CMYK by its component count; the profile itself is not applied), `/Decode` arrays, and image masks, which come out black where they paint and transparent elsewhere. A soft mask, a stencil mask and a colour-key mask all become the alpha channel; a mask of another size is resampled to the image. CMYK is converted with the plain `(1 - c)(1 - k)` formula, so colours differ from a colour-managed viewer.

CCITT and JBIG2 `bytes` are the raw coded data without a file header: CCITT needs `decodeParms` (`K`, `Columns`, `Rows`, `BlackIs1`) to be decoded and JBIG2 needs `jbig2Globals` when the document has them.

In the viewer, `extractImages` returns a promise and can fill in what the package cannot decode by sampling the rendered page:

```ts
const images = await viewer.extractImages(0, { renderFallback: true });
for (const image of images) {
  if (image.isRendered) console.info(`${image.name} is an approximation taken from the rendered page`);
}
```

With `renderFallback: true`, an image without `data` gets pixels cut from a rendering of the page at the image's own resolution, and `isRendered: true`. Its `status` stays `encoded-only` or `unsupported`, because the pixels are not the image data: anything drawn over the image, and any clipping, is part of them, and they are opaque.

Extraction needs the `copy` permission of a protected document. Images inside form XObjects and in annotation appearances are not listed.

## Reading text in reading order

`extractText` returns the characters in the order of the content stream. `getStructuredText(pageIndex, options)` returns lines and words in reading order, each with its geometry and font, for copying with formatting, for reading a page aloud and for marking up rotated text.

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

const page = pdf.getStructuredText(0);
for (const line of page.lines) console.info(line.rotation, line.fontSize, line.text);

const words = pdf.extractTextItems(0);
const heading = words.filter((word) => word.isBold && word.fontSize >= 14);
pdf.addAnnotation({
  type: 'highlight',
  pageIndex: 0,
  rect: heading[0].rect,
  quadPoints: quadPointsFromQuads(heading.map((word) => word.quad)),
});
```

| `PageTextItem` (a word) | Meaning |
| --- | --- |
| `text` | The word, in logical order |
| `rect`, `quad` | Bounding rectangle, and the four corners in the orientation of the text: bottom left, bottom right, top right, top left as a reader of that text sees them |
| `baseline` | Start and end point of the baseline; the centre line for vertical writing |
| `fontName`, `fontSize` | Font name without the subset prefix, and the size on the page in points |
| `isBold`, `isItalic` | A guess from the font name and the font flags |
| `rotation` | Direction of the text in degrees, counter-clockwise; `90` for text that reads from bottom to top |
| `direction` | `ltr`, `rtl`, or `ttb` for vertical writing |
| `lineIndex`, `hasSpaceAfter` | The line it belongs to, and whether a space follows |
| `charQuads` | One quad per character, with the option `charQuads: true` |

A `PageTextLine` has `text`, `rect`, `quad`, `baseline`, `fontSize`, `rotation`, `direction` and its `items`. The result also has all `items` in order and the page `text` with one line per line.

- `quadPointsFromQuads(quads)` turns quads into the `quadPoints` of a text markup annotation, so highlights follow rotated and vertical text.
- Lines are ordered top to bottom. Blocks that sit next to each other are read as columns when they are at least three lines long and the lines fill their column; otherwise they are read row by row, as in a table. `order: 'content'` keeps the order of the content stream.
- Lines with different rotations are grouped per direction. Vertical columns are read from right to left.
- Text inside form XObjects is included. Text under applied redactions is left out.

## Geometry for snapping

`getPageGeometry(pageIndex, options)` returns what a drawing tool can snap to, in PDF user space:

```ts
const geometry = pdf.getPageGeometry(0);
console.info(geometry.points.length, geometry.segments.length, geometry.baselines.length, geometry.isTruncated);
```

| `PageGeometry` | Meaning |
| --- | --- |
| `points` | End points of the lines and curves of stroked and filled paths, rectangle corners and image corners |
| `segments` | Straight edges as `[x1, y1, x2, y2]`: path lines, rectangle and image edges, and the closing edge of filled shapes |
| `baselines` | One `[x1, y1, x2, y2]` per text run, along its baseline |
| `textBoxes` | The `rect` and the rotated `quad` of each text run |
| `isTruncated` | `true` when a limit was reached or the content could not be read to the end |

Form XObjects are walked with their transformation. Clipping paths are ignored, curves contribute their end points only, duplicates within a tenth of a point are removed, and segments shorter than half a point are dropped. Points outside the crop box are left out. The limits are `maxPoints` and `maxSegments` (4000 each) and `maxTextRuns` (2000); `includePaths`, `includeText` and `includeImages` switch a kind off. The result is cached until the page content changes.

## Text style

`restylePageText(pageIndex, run, style)` draws a run again with another font, size, colour or face. `style` takes `font`, `fontSize`, `color`, `isBold` and `isItalic`; what you leave out stays as it is.

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

declare const bytes: Uint8Array;
declare const notoSans: Uint8Array;
const pdf = openPdfDocument(bytes, { fonts: [{ name: 'Noto Sans', data: notoSans }] });

const heading = pdf.getTextRuns(0).find((run) => run.text === '1. Services');
if (heading) pdf.restylePageText(0, heading, { isBold: true, fontSize: 16, color: '#b3261e' });

const clause = pdf.getTextRuns(0).find((run) => run.text.startsWith('The initial term'));
if (clause) pdf.restylePageText(0, clause, { font: 'Noto Sans' });
console.info(pdf.getSuppliedFontNames());
```

- `font` is a standard family (`Helvetica`, `Times-Roman`, `Courier`, or one of their bold and italic faces) or the name of a font you supplied with `fonts`. A supplied font is embedded as a subset that holds only the glyphs of the run.
- `isBold` and `isItalic` pick the matching face when the run is in a standard family (Helvetica or Arial, Times, Courier). For any other font the bold is drawn with a thin outline in the fill colour and the italic with a slant, and the result has `isSynthetic: true`.
- The run is drawn again at the end of the page content, in the same place, so it is on top of content that used to cover it. The result carries `rect`, the new bounding box.

## Find and replace

`findEditableText(query, options)` returns every match in text that can be edited, with the page, the text around it and its rectangle. `replaceText(query, replacement, options)` replaces all of them, or only the ones you pass in `matches`, as one undo step.

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

declare const bytes: Uint8Array;
const pdf = openPdfDocument(bytes);

const matches = pdf.findEditableText('Provider', { matchCase: true, wholeWord: true });
for (const match of matches) console.info(match.pageIndex + 1, `${match.before}[${match.text}]${match.after}`);

const result = pdf.replaceText('Provider', 'Northwind Analytics', { matchCase: true, wholeWord: true });
console.info(result.replaced, result.pages, result.failed);
pdf.undo();
```

- The query is plain text, not a pattern. A space in it also matches the line break inside a paragraph.
- A match inside a recognised paragraph (`scope: 'paragraph'`) is replaced by reflowing the paragraph. When the paragraph needs more lines than before, the text, images and shapes under it in the same column move down by the difference; if that would push something off the page, nothing is moved and the paragraph overflows as described under [Limits](#limits). Other matches (`scope: 'run'`) rewrite one run in place.
- `failed` lists the matches that could not be written, for example because the font has no shape for a character of the replacement; the other matches are still replaced.
- Text of headers, footers and watermarks is included. The invisible text layer of a scanned page is not.

## Page objects

`getPageObjects(pageIndex)` lists what the page content draws, in paint order: text runs, images, vector shapes (`path`), form XObjects (`form`), shadings and inline images. Each object has an `id`, its `kind`, a `rect`, a `label` (the text, the resource name or how a shape is painted) and, for content of a header, footer, watermark, background, page number or Bates number, the `layer` it belongs to.

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

declare const bytes: Uint8Array;
const pdf = openPdfDocument(bytes);

const objects = pdf.getPageObjects(0);
const rule = objects.find((object) => object.kind === 'path' && object.label === 'stroke');
if (rule) {
  const moved = pdf.movePagePath(0, rule, { dx: 0, dy: -24 });
  if (moved.ok && moved.object) pdf.reorderPageObject(0, moved.object, 'front');
}
const box = pdf.getPageObjects(0).find((object) => object.kind === 'path' && object.label === 'fill');
if (box) pdf.deletePagePath(0, box);
```

- `movePagePath` and `deletePagePath` work on vector shapes. A shape that also sets the clipping area for later content (`hasClip`) cannot be moved or reordered; deleting it stops it from being painted and keeps the clip.
- `reorderPageObject(pageIndex, object, 'front' | 'forward' | 'backward' | 'back')` works on images and shapes. The object keeps its place, its colours and its line style. `forward` and `backward` step over one painted object; an object inside a clipped group or a text block is stepped over together with that group.

### Image opacity, crop and rotation

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

declare const bytes: Uint8Array;
const pdf = openPdfDocument(bytes);

const [photo] = pdf.getPageImages(0);
if (photo) {
  pdf.rotatePageImage(0, photo, 90);
  const [turned] = pdf.getPageImages(0);
  pdf.cropPageImage(0, turned, [0, 0, 0.5, 1]);
  const [cropped] = pdf.getPageImages(0);
  pdf.setPageImageOpacity(0, cropped, 0.6);
  console.info(pdf.getPageImages(0)[0].visibleRect);
}
```

- `rotatePageImage` turns the image about its centre, counter-clockwise for a positive angle.
- `cropPageImage` takes the part to keep in image space, `[x0, y0, x1, y1]` from 0 to 1 with the origin in the lower left corner of the image, or `null` to show all of it again. The crop is a clipping rectangle: the pixels outside it stay in the file. Use [redaction](https://docs.birchui.com/pdf/redaction.md) to remove them.
- `setPageImageOpacity` sets a constant opacity from 0 to 1.
- `getPageImages` reports `opacity`, `crop` and `visibleRect` for images changed this way.

## Headers, footers, watermarks and backgrounds

Everything `addWatermark`, `addHeaderFooter`, `addPageNumbers`, `addBatesNumbers` and `addBackground` draw is marked in the page content as an artifact with its kind and the options it was made with. `getPageDecorations()` finds these marks, and the standard marks other programs write for headers, footers, watermarks and backgrounds.

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

declare const bytes: Uint8Array;
const pdf = openPdfDocument(bytes);

pdf.addBackground({ color: '#fff8e1' });
pdf.addWatermark({ text: 'DRAFT', opacity: 0.3, rotation: 45 });
for (const item of pdf.getPageDecorations()) console.info(item.kind, item.pages, item.isOwn, item.options);

pdf.removePageDecorations('watermark', [0]);
pdf.removePageDecorations(['header', 'footer']);
```

- A decoration has a `kind` (`watermark`, `header`, `footer`, `background`, `pageNumbers` or `bates`), the `pages` that carry it, `isOwn` and, when this package made it, the `options` it was made with. Pages with the same options are reported as one entry.
- `removePageDecorations(kinds, pages?)` removes the marked content and returns the number of pages it changed. To change a decoration, remove it and add it again with new options; the viewer does this in one undo step.
- `addWatermark` also takes an image: `addWatermark({ data, width, opacity })`.
- The marks survive saving, and editing other content of the page. A header that another program drew without marking it is ordinary text; edit or delete it as text.

## Text on scanned pages

Experimental. A page that went through [text recognition](https://docs.birchui.com/pdf/ocr.md) has an invisible text layer. `replaceScannedText(pageIndex, run, text, options)` takes one of its runs (`isInvisible: true` in `getTextRuns`), paints a patch in `background` over the area of the word, removes the invisible run and types `text` as visible text in its place.

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

declare const bytes: Uint8Array;
const pdf = openPdfDocument(bytes);

const word = pdf.getTextRuns(0).find((run) => run.isInvisible && run.text.trim() === 'lnvoice');
if (word) pdf.replaceScannedText(0, word, 'Invoice', { background: '#f4f1ea', color: '#1f2328' });
```

The scan under the patch is covered, not removed, the typed text uses a standard or supplied font and not the typeface of the scan, and the patch has one flat colour. In the viewer the colour is sampled from the pixels around the word.

## In the viewer

The **Edit content** tool group has three tools. They need the `modify` permission of the document and are not offered when the viewer is `readOnly`.

| Tool | `tool` | What it does |
| --- | --- | --- |
| Edit text | `editText` | Every text run on the visible pages gets a focusable outline. Click a run to edit it in place: `Enter` commits, `Escape` cancels, and an empty text deletes the run. Drag a run to move it. With a run focused, `Delete` removes it and the arrow keys move it by 1 pt (`Shift`: 10 pt). A paragraph of two or more lines also gets a **¶** button at its left edge: click it, or press `Enter` on it, to edit the whole paragraph in a multi-line box. `Enter` starts a new line there, `Ctrl+Enter` (`Cmd+Enter`) applies the text and reflows it, `Escape` cancels. A message says so when the paragraph has become longer than its original block. |
| Add text | `addText` | Click the page and type; `Enter` places the line with the font size and colour chosen in the style bar. |
| Edit images | `editImage` | Click an image to select it, drag it to move it, drag a handle to resize it, press `Delete` to remove it. **Add image…**, **Replace image…**, **Delete image**, **Rotate image left**, **Rotate image right** and **Image properties…** (opacity, crop and order) are in the tool row. Vector shapes get an outline too: click one to select it, drag it or use the arrow keys to move it, press `Delete` to remove it. Shapes that cover the whole page or belong to a header, footer or watermark have no outline; they are in the object list. |

The tool row of the Edit tab also has:

| Button | What it does |
| --- | --- |
| **Text style…** | Font, size, colour, bold and italic for the text run that was clicked or focused last, or for its whole paragraph. The font list holds the standard families and the fonts given in the `fonts` option. |
| **Find and replace…** | Finds text across the document and lists every match with the text around it and what it will become. Untick the matches to keep, then **Replace selected** or **Replace all**. One undo step takes the whole replacement back. |
| **Page objects** | Opens the **Page objects** panel of the sidebar: every object of the current page from front to back, with the header, footer or watermark it belongs to. Click an entry to select the object on the page; the bin next to it deletes it. |
| **Background…** | A page colour behind the content of every page. |
| **Headers, footers and watermarks…** | Lists the headers, footers, watermarks, backgrounds, page numbers and Bates numbers that were recognised, with their pages. **Edit** opens the dialog the decoration was made with, filled in; **Delete** removes it. |

In the Edit text tool the recognised words of a scanned page have a dotted outline. Editing one replaces it as described under [Text on scanned pages](#text-on-scanned-pages); this is experimental.

A link is changed from its context menu (**Edit link…**), added with the Link tool of the Comment tab and removed with `Delete`. Bookmarks are added, renamed, pointed at the current page and deleted in the **Bookmarks** panel of the sidebar.

Each change is one undo step, and the page is rendered again after the change and after undo and redo. When the font of a run has no shape for a typed character, or cannot be written to, nothing is changed and a message says so; when a supplied or standard font had to be used instead of the original one, the message names it.

The same operations are methods of the viewer. They resolve after the rendered page has been refreshed:

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

const viewer = createPdfViewer(document.querySelector<HTMLElement>('#contract')!, { document: bytes });
await viewer.ready;

const run = viewer.getTextRuns(0).find((item) => item.text === 'thirty (30) days');
if (run) {
  const result = await viewer.editPageText(0, run, 'forty-five (45) days');
  if (!result.ok) console.warn(result.reason, result.missing);
}
await viewer.addPageText(0, { text: 'Amended 27 November 2026', x: 72, y: 60, fontSize: 9 });

const [logo] = viewer.getPageImages(0);
if (logo) await viewer.movePageImage(0, logo, { dx: 0, dy: -12 });
viewer.undo();
```

`getTextParagraphs`, `editPageParagraph`, `deletePageText`, `movePageText`, `addPageImage`, `replacePageImage` and `deletePageImage` follow the same pattern. `viewer.addPageImage` and `viewer.replacePageImage` accept every format in the [table above](#image-formats) and convert it for you; **Add image…** and **Replace image…** in the tool row, the Image tool and the image tab of the signature dialog do the same, and announce a message when a file cannot be read as an image. The `fonts` option of the viewer supplies the fonts for characters the original font lacks; see [Fonts](https://docs.birchui.com/pdf/fonts.md#in-the-viewer).

## Limits

- **Pushing content down is opt-in and stops at the page.** `editPageParagraph(..., { pushBelow: true })` and `replaceText` move the text, images and shapes under a paragraph that grew, in the same column, down by the difference. Annotations and form fields stay where they are, nothing moves to the next page, and when the lowest object would come closer than 18 pt to the bottom of the page nothing is moved.
- **Restyled text is drawn on top.** Like a rewritten paragraph, a restyled run is written again at the end of the page content. Bold and italic for fonts outside the standard families are imitated with an outline and a slant.
- **Find and replace works block by block.** A match that starts in one paragraph or run and ends in another is not found.
- **Cropping an image hides pixels; it does not remove them.**
- **Shapes are moved, deleted and reordered whole.** Their points, colours and line style cannot be changed, and a shape inside a form XObject is not listed.
- **Reflow stays inside one column.** `editPageParagraph` breaks the new text into lines within the width of the block. With `pushBelow: true`, which the viewer uses, the text, images and shapes under the paragraph in the same column move down when it needs more lines; without it the paragraph continues downwards over what is there. Text does not flow on to the next column or page.
- **Simple paragraphs only.** Upright, horizontal text in one font and size whose lines are left-aligned, right-aligned, centred or justified. A paragraph with a bold word in it, a first-line indent, hanging bullets or a drop cap is not recognised as one block; its lines appear as separate runs. In the viewer such a line is edited on its own, and the editor says so when you open it: a longer line does not wrap and does not move the lines below.
- **The paragraph is written again at the end of the page content**, after everything else, so it is drawn on top of content that used to be drawn over it. The original runs are emptied in place.
- **Editing a single run does not reflow.** With `editPageText` a longer replacement does not wrap and does not push the next line down. A sentence that the producer split into several runs is edited piece by piece unless you edit its paragraph.
- **There is no method to find the run or image under a point**; filter `getTextRuns()` and `getPageImages()` by `rect` yourself. The viewer does this for the pointer.
- **Outlines follow the bounding box.** In the viewer the outline of a rotated run or image is its upright bounding box, and images are resized along the page axes.
- **Images inside form XObjects and inline images** are not listed by `getPageImages` and cannot be edited. `extractImages` does return inline images, but not those inside form XObjects.
- **Animated GIF, multi-page TIFF.** Only the first frame or image is used. Tiled TIFF, TIFF with JPEG, CCITT or other compression, and CMYK or planar TIFF are rejected.
- **Colour profiles and metadata of added images are dropped.** An embedded ICC profile, gamma, EXIF orientation and resolution are not applied or stored; rotate or size the image with `rect` and `rotation`.
- **Vector images are rasterised.** An SVG becomes pixels at the size the decoder chose; it is not converted to PDF drawing operators.
- **Moving text** translates a run. It does not rotate or scale it, and a moved run can end up over other content.
- **Reading order is a heuristic.** Tables whose cells fill their columns can be read column by column, and unusual layouts (text around pictures, more than one text direction per block) can come out in a different order than a person would read. Right-to-left lines are reversed as a whole, without the full bidirectional algorithm. Vertical writing uses the default vertical metrics of the font (`DW2`), not per-glyph ones.
- **Subset fonts.** Most files embed only the glyphs they use. If the invoice never contained a `7`, the font has no `7`, and replacing `48` with `47` needs a supplied font. The replacement run then uses that font and can look slightly different from its neighbours.
- **Fonts that cannot be written to.** Type 3 fonts, composite fonts without a ToUnicode map or with an encoding other than Identity-H or Identity-V, symbolic fonts without a ToUnicode map and simple fonts with a MacRoman or MacExpert encoding without a ToUnicode map are refused unless a supplied font takes over.
- **Kerning is not preserved.** A run written as a kerned array is replaced by a plain string, so pair kerning inside that run is lost. Character and word spacing stay in effect.
- **Text inside form XObjects** (repeated headers, some charts, content of other producers' stamps) is found by text search and `getStructuredText` but not by `getTextRuns`, and cannot be edited.
- **Vertical writing** can be read, searched, redacted and moved, but its text cannot be replaced reliably. Text drawn as outlines or as an image cannot be edited.
- **Right-to-left text** is supported for new and replacement text through a supplied font, with basic reordering. Existing right-to-left runs are edited in the order the producer stored them.
- **Tagged PDF.** The structure tree is not updated. Edited text keeps its marked-content tags, and added text and images are not tagged.
- **Width calculation** uses the widths stored in the PDF. For the standard fonts only Helvetica, Helvetica-Bold and Times-Italic metrics are built in; the reported rectangle of added text in the other standard faces is an estimate, the placement itself is exact.
- **Earlier revisions keep the old text.** After an incremental save the replaced text is still in the file. To remove sensitive text, use [redaction](https://docs.birchui.com/pdf/redaction.md), which rewrites the file.
