# Forms

> Fill AcroForm fields, validate them, run Acrobat format, keystroke, calculation and validation scripts without executing JavaScript, read submit and reset actions as data, exchange form data as FDF, XFDF, JSON and XML, design fields and flatten a finished form.

Birch UI PDF reads the AcroForm of the opened document and draws an HTML control over each widget: text inputs and text areas, checkboxes, radio groups, drop-downs, list boxes and signature buttons. Values are written back into the PDF with fresh appearance streams. `enableForms: false` hides the controls and the Form fields panel.

XFA forms are not supported. See [Limitations](https://docs.birchui.com/pdf/limitations.md#forms).

## Reading and writing values

```ts
viewer.getFormFields();
viewer.getFormValues();

viewer.setFormValues({
  'client.name': 'Fabrikam Logistics GmbH',
  'client.date': '03/03/2026',
  accept: true,
  billing: 'Monthly',
  services: ['Analytics', 'Training'],
});

viewer.on('formFieldChange', ({ name, value, previousValue, source }) => {
  console.info(name, previousValue, '→', value, source);
});
```

| Field type | Value |
| --- | --- |
| `text` | string |
| `checkbox` | `true` or `false` |
| `radio` | the export value of the selected button, or `null` |
| `combo` | the export value |
| `list` | a string, or an array of strings for multi-select lists |
| `signature`, `button` | `null` |

Names are fully qualified, as in `fee.monthly`. An unknown name produces a console warning and is skipped. A fill and the calculations it triggers are one undo step, and `formFieldChange` fires once for every field whose value changed, calculated fields included. `resetForm()` puts every field back to its default value.

In the headless API, `setFormValue` and `setFormValues` return the names of the fields that changed, and `getFormField(name)` returns one field.

`setFormValue` and `setFormValues` do not store a number outside the `range` of a field: the value is left as it was, a console warning names the field, and the `formFieldReject` event of a headless document carries `{ name, value, issue }`. Values typed in the viewer are stored and flagged on the control instead, so the user can see and correct them.

## Scripts that run

Birch UI PDF never executes JavaScript from a document: there is no `eval` and no `new Function` anywhere in the package. A script is read with a tokenizer and a parser that accept a fixed grammar, and the package runs its own equivalent code. A script that does not fit is reported as unsupported, is not run, and stays in the file unchanged.

### Recognised Acrobat functions

A script made only of the calls below, with literal arguments, is recognised (`kind: 'builtin'`).

| Trigger | Functions |
| --- | --- |
| Format and keystroke | `AFNumber_Format`, `AFNumber_Keystroke` (decimals, separator style 0 to 4, negative style, currency text, currency before or after) |
| | `AFPercent_Format`, `AFPercent_Keystroke` |
| | `AFDate_FormatEx`, `AFDate_KeystrokeEx` (pattern), `AFDate_Format`, `AFDate_Keystroke` (index 0 to 13 of the Acrobat date table) |
| | `AFTime_FormatEx`, `AFTime_KeystrokeEx` (pattern), `AFTime_Format`, `AFTime_Keystroke` (index 0 to 3) |
| | `AFSpecial_Format`, `AFSpecial_Keystroke` (0 ZIP, 1 ZIP+4, 2 phone, 3 social security number) |
| | `AFSpecial_KeystrokeEx` (mask: `9` digit, `A` letter, `O` letter or digit, `X` any printable character, anything else literal) |
| Validate | `AFRange_Validate(hasMin, min, hasMax, max)` |
| Calculate | `AFSimple_Calculate` with `SUM`, `PRD`, `AVG`, `MIN` or `MAX` and `new Array("a", "b")`, `["a", "b"]` or `"a, b"` |
| Any | `AFMergeChange(event)`, accepted and ignored |

The call must be the whole script. `if (x) AFNumber_Format(…)`, a computed argument, or a recognised call followed by any other statement makes the script unsupported.

### Safe expression subset

Custom calculation, validation and format scripts run when they fit this grammar (`kind: 'expression'`):

- Statements: `event.value = …;`, `event.rc = …;`, `var`/`let`/`const name = …` (several per statement), `name = …`, the compound forms `+=`, `-=`, `*=`, `/=`, `if (…) … else …`, blocks in braces, and `app.alert(message)`. Statements end with a semicolon; automatic semicolon insertion is not supported.
- Values: numbers, strings in single or double quotes, `true`, `false`, `null`, `event.value`, local variables, `this.getField("name").value`, `getField("name").value` and `.valueAsString`. The field name must be a string literal.
- Operators: `+ - * / %`, unary `-`, `+` and `!`, parentheses, `== != === !== < <= > >=`, `&&`, `||`, `? :`. `+` joins text when either side is text, as in JavaScript.
- Functions: `Number`, `parseFloat`, `parseInt`, `String`, `isNaN`, `AFMakeNumber`, `Math.round`, `Math.floor`, `Math.ceil`, `Math.abs`, `Math.sqrt`, `Math.pow`, `Math.min`, `Math.max`.
- Methods and properties on a value: `.toFixed(n)`, `.toString()`, `.toUpperCase()`, `.toLowerCase()`, `.trim()`, `.length`.

Everything else is rejected: other function calls, property access (including `constructor` and `__proto__`), `new`, arrays, objects, template strings, loops, function definitions, assignment to anything but `event.value`, `event.rc` and local variables. A script is also rejected when it is longer than 16,384 characters, has more than 4,096 tokens or nests deeper than 48 levels, so parsing and running take bounded time.

How each trigger uses a script:

- **Calculate**: the script must assign `event.value`. A number result is rounded to ten decimals; text is stored as it is.
- **Validate**: `event.value` holds the value being checked. When the script sets `event.rc` to a false value, the value is invalid. Messages passed to `app.alert` are never shown by the engine; they are returned as the validation message.
- **Format**: the script must assign `event.value` and must not read other fields. The result is the text shown while the field is not focused.
- **Keystroke**: only the recognised functions run. A custom keystroke script is always unsupported.

A field value read by a script is a number when the text is numeric, as in Acrobat, so an empty field is `""` and `"" + 5` is `"5"`. Use `Number(...)` in sums.

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

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

const report = pdf.describeFieldScripts('fee.total');
if (report) {
  for (const trigger of ['format', 'keystroke', 'validate', 'calculate'] as const) {
    const { status, kind, source } = report[trigger];
    console.info(trigger, status, kind, source);
  }
}
```

`describeFieldScripts(name)` returns, for each of the four triggers, `status` (`supported`, `unsupported` or `none`), `kind` (`builtin`, `expression`, `custom` or `none`) and the script `source`, so an application can tell the user that a form contains scripts that will not run. `classifyScript(trigger, source)` does the same for one script.

Formatted values are shown while a field is not focused; the raw value is edited. Calculated fields are computed once when the document opens, which does not mark it as modified or add an undo step, and again after every change, in the document's calculation order. A signed document, or one that does not permit filling, opens with its stored values.

## Validation

`validateForm()` checks every field and returns the problems in field order. Each entry has the field `name`, the `pageIndex` and `rect` of its first widget, a `code`, a message `key` with `params`, and a default English `message`.

| `code` | `key` | `params` |
| --- | --- | --- |
| `required` | `required` | |
| `maxLength` | `maxLength` | `max` |
| `format` | `number`, `date`, `time` | `pattern` for dates and times |
| `range` | `rangeMin`, `rangeMax` | `min` or `max` |
| `pattern` | `special`, `mask` | `format` or `mask` |
| `script` | `script` | `message`: the text the script passed to `app.alert`, or empty |

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

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

const german: Partial<Record<FormMessageKey, string>> = {
  required: 'Dieses Feld ist erforderlich.',
  rangeMax: 'Geben Sie höchstens {max} ein.',
};
for (const issue of pdf.validateForm()) {
  console.info(issue.name, issue.pageIndex, issue.rect, formatFormMessage(issue.key, issue.params, german));
}

pdf.updateFormField('client.name', { isRequired: true });
const state = pdf.getFormState();
console.info(state.isDirty, state.dirtyFields, state.isValid, state.requiredFilledCount, state.requiredCount);
```

`validateFormField(name, value?)` returns the message for one field and `validateFormFieldIssue(name, value?)` the whole entry. In the viewer, the message of a field appears next to its control; see [Validation in the viewer](#validation-in-the-viewer). A required signature field counts as empty until it holds a digital signature. `isRequired` is the `Required` field flag (`Ff` bit 2) and is written back on save.

`getFormState()` returns `isDirty` and `dirtyFields` (values that differ from the document as opened or last saved), `isValid`, and the counts `fieldCount`, `filledCount`, `requiredCount` and `requiredFilledCount`. Buttons, signature fields and barcode fields are not counted.

### Keystroke filtering

`filterKeystroke(name, currentValue, change, selStart, selEnd?)` applies the keystroke rule of a field to one edit, where `change` replaces the selection. It returns `{ isAccepted, value, selStart, selEnd, key? }`: the new value and caret when the edit is accepted, the unchanged value and the message `key` when it is not.

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

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

input.addEventListener('beforeinput', (event) => {
  const start = input.selectionStart ?? input.value.length;
  const end = input.selectionEnd ?? start;
  const result = pdf.filterKeystroke('fee.monthly', input.value, event.data ?? '', start, end);
  if (!result.isAccepted) event.preventDefault();
});
```

A custom keystroke script runs when it stays inside the [safe expression subset](#safe-expression-subset) and assigns `event.rc` or `event.change`; it can read `event.value`, `event.change`, `event.willCommit`, `event.selStart` and `event.selEnd`. A script that upper-cases what is typed (`event.change = event.change.toUpperCase();`) or refuses it (`event.rc = false;`) therefore works; anything outside the grammar is left in the file and not run.

Number and percent fields accept digits, one sign and the decimal separator of their separator style. Date and time fields accept the characters their pattern can produce. ZIP, ZIP+4, phone and social security fields accept digits in their layout. A mask is applied character by character, and literal characters of the mask are inserted for the user. `maxLength` (also for comb fields) truncates a paste and rejects typing into a full field. `filterFieldKeystroke(field, …)` is the same function for a field object.

### Validation in the viewer

While the user types, the viewer passes every insertion through `filterKeystroke`. A rejected key leaves the value as it is and shows a short hint below the field, such as "Enter a number.". When the user leaves a field, or changes a check box, radio button or list, the field is validated; a problem is shown below the control, the control gets `aria-invalid="true"` and the message is tied to it with `aria-describedby` and announced. The message goes away as soon as the value is valid.

Required fields carry `aria-required` and a red frame. The frame can be switched off with **Highlight required fields** in the Form fields panel or with `highlightRequiredFields: false`.

**Check the form** in the Form fields panel and in the menu runs `validateForm()`, marks every field that has a problem and lists the problems in the panel under **Form problems**. Choosing an entry scrolls to the field and moves the focus into it. The list updates while the user fixes the values.

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

declare const container: HTMLElement;
declare const bytes: Uint8Array;
const viewer = createPdfViewer(container, {
  document: bytes,
  highlightRequiredFields: true,
  labels: { formMessageRequired: 'Dieses Feld ist erforderlich.', formProblems: 'Probleme im Formular' },
});

viewer.on('formValidation', ({ issues, isValid }) => {
  console.info(isValid, issues.map((issue) => `${issue.name}: ${issue.key}`));
});
const issues = viewer.validateForm();
if (issues.length === 0) await viewer.download();
```

Every message has a label key: `formMessageRequired`, `formMessageMaxLength`, `formMessageNumber`, `formMessageRangeMin`, `formMessageRangeMax`, `formMessageDate`, `formMessageTime`, `formMessageSpecial`, `formMessageMask`, `formMessageScript`, `formMessageOption` and `formMessageReadOnlyType`, with the same placeholders as the engine messages. A validation script that passes its own text to `app.alert` shows that text.

## Actions, submit and reset

The engine reads the actions of a field and of its widgets into data. It never follows a link, runs a script or contacts a server.

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

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

for (const { trigger, action } of pdf.getFieldActions('submitButton')) {
  if (trigger !== 'activate') continue;
  if (action.type === 'resetForm') pdf.resetForm(action.fields, { exclude: action.isExclude });
  if (action.type === 'submitForm') {
    const payload = await pdf.buildSubmitPayload(action);
    console.info(payload.url, payload.method, payload.format, payload.contentType, payload.fieldNames);
  }
}
```

`getFieldActions(name)` returns `{ trigger, widgetIndex?, action }` entries. `trigger` is `activate` for the widget's `/A` action, or `mouseUp`, `mouseDown`, `mouseEnter`, `mouseExit`, `focus`, `blur`, `keystroke`, `format`, `validate` or `calculate` for `/AA`. Chained `/Next` actions follow their parent, up to 32 per chain.

| `action.type` | Fields |
| --- | --- |
| `submitForm` | `url`, `flags`, `format` (`fdf`, `xfdf`, `html` or `pdf`), `method`, `fields`, `isExclude`, `includeEmpty` |
| `resetForm` | `fields`, `isExclude` |
| `javaScript` | `script` |
| `named` | `name`, such as `NextPage` or `Print` |
| `goTo` | `pageIndex` or a named `destination` |
| `uri` | `uri` |
| `hide` | `fields`, `isHidden` |
| `other` | `subtype` |

`resetForm(names?, { exclude? })` sets fields back to their default values and returns the names that changed. A name selects a field or every field below it, so `client` covers `client.name`. With `exclude`, every field except the listed ones is reset. Without names the whole form is reset. It is one undo step, and the session emits `formReset` with `{ names, changed, source }`.

`buildSubmitPayload(action)` returns `{ url, method, format, body, contentType, fieldNames }` and sends nothing. The body is FDF bytes (`application/vnd.fdf`), an XFDF string (`application/vnd.adobe.xfdf`), a URL-encoded string (`application/x-www-form-urlencoded`) or the saved PDF (`application/pdf`). `method` is `get` only for an HTML submit with the `GetMethod` flag; append the body to the URL yourself. The field list and the include/exclude flag of the action are honoured, fields without a value are left out unless the action includes them, and password and no-export fields are never part of a payload. `submitForm(action, fieldName?)` builds the payload and emits `formSubmit` with `{ action, payload, fieldName? }` on the session; the application decides whether and how to send it. Check `payload.url` before you use it: it comes from the document.

### Buttons in the viewer

A push button with an action is a real button in the viewer. Activating it runs its actions in order:

| Action | What the viewer does |
| --- | --- |
| `resetForm` | Calls `resetForm` with the field list of the action, as one undo step, and emits `formReset` |
| `submitForm` | Builds the payload and emits `formSubmit`. Nothing is sent. |
| `goTo`, `named` | Goes to the page; `NextPage`, `PrevPage`, `FirstPage`, `LastPage` and `Print` are understood |
| `uri` | Shows the same confirmation dialog as a link annotation; unsafe schemes are refused |
| `javaScript` | Runs only scripts made of `this.resetForm()`, `this.resetForm(["a", "b"])`, `this.print()`, `this.pageNum = n`, `this.pageNum++`, `this.pageNum--`, `this.submitForm("url")` and `app.beep()`. Any other script is skipped as a whole. |
| `hide`, `other` | Nothing |

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

declare const container: HTMLElement;
declare const bytes: Uint8Array;
const viewer = createPdfViewer(container, { document: bytes });

viewer.on('formSubmit', async ({ url, method, body, contentType, format, fieldName }) => {
  if (new URL(url).origin !== 'https://orders.northwind-analytics.co.uk') return;
  console.info(`Sending ${format} from ${fieldName ?? 'code'}`);
  await fetch(url, { method: method.toUpperCase(), headers: { 'Content-Type': contentType }, body: body });
});
viewer.on('formReset', ({ names, changed }) => console.info(names.length, changed));
viewer.resetForm(['fee']);
```

The `formSubmit` payload is `{ url, method, format, body, contentType, fieldNames, fieldName? }`. The URL comes from the document, so check it before you send anything. `viewer.resetForm(names?)` resets the listed fields, or the whole form, and emits `formReset` with `{ names, changed }`.

## Field features

- **Comb fields.** `isComb: true` with a `maxLength` draws each character in its own evenly spaced cell. A comb field cannot be multi-line or a password field; without `maxLength` the flag is ignored.
- **Rich text fields.** A text field with `richText` paragraphs (the same model as [rich text in text boxes](https://docs.birchui.com/pdf/annotations.md#rich-text-in-text-boxes)) is written with the `RichText` flag, `/RV`, `/DS` and a matching appearance. `value` is always the plain text. Setting a plain value replaces the formatting.
- **Check boxes and radio buttons.** A widget has `onValue`, the name of its on state, and `exportValue` when the field maps states to export values with `/Opt`. The value of a radio group is the on state of the selected button, so two buttons with the same export value stay distinct. `isRadiosInUnison` and `isNoToggleToOff` report the flags of a group and are kept on save. A check box field whose widgets have different on states behaves as one choice: its value is the on state, or `false`. State names with spaces, `#`, `/` or non-ASCII characters round-trip. When a field has no `/V`, the state comes from `/AS`; `/AS` is rewritten to match the value when the field is saved.
- **List boxes.** Multi-select values are arrays, written as an array `/V` with the sorted `/I` indices. A list without `/V` is read from `/I`.
- **Combo boxes.** An editable combo box accepts any text. For other combo boxes and for lists and radio groups, an import rejects a value that is not one of the choices.
- **Colours.** `borderColor` and `backgroundColor` of a field are hex colours or `null` for none. They are read from the first widget (`/MK`), can be passed to `addFormField` and `updateFormField`, and are written to every widget of the field with a new appearance.
- **Rotated pages and rotated fields.** In the viewer a control is laid out in the unrotated box of its field and turned with the page, so on a page rotated by 90° (saved rotation, **Rotate view**, or both) the value reads along the field and the caret, the selection and the focus ring follow it. A widget with its own rotation (`/MK /R`) reports it as `rotation` (`90`, `180` or `270`) on the widget; the control is turned back by that amount and the saved appearance is drawn along the field with a matching `/Matrix`.
- **Hidden widgets.** A widget with the Hidden or NoView flag (`isHidden`) is not shown on the page or on its thumbnail. The form designer still lists it and draws its box, so it can be changed.
- **Flags on export.** Password fields and fields with the `NoExport` flag (`isNoExport`) are never exported or submitted. Read-only fields and hidden widgets (`isHidden` on the widget) are exported, as in other PDF applications.
- **Barcode fields are not supported.** A dynamic barcode field (PDF417, QR Code or Data Matrix) is reported as a read-only text field with `barcode: { symbology }`, and `fieldKind(field)` returns `'barcode'`. The engine does not draw, fill, validate or export it, and leaves it untouched in the file.

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

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

pdf.addFormField({
  name: 'iban.check',
  type: 'text',
  pageIndex: 0,
  rect: [100, 500, 220, 520],
  isComb: true,
  maxLength: 6,
});
pdf.addFormField({
  name: 'delivery.notes',
  type: 'text',
  pageIndex: 0,
  rect: [72, 400, 372, 460],
  isMultiline: true,
  richText: [{ runs: [{ text: 'Deliver to ' }, { text: 'Dock 4', bold: true }] }],
});
const unsupported = pdf.getFormFields().filter((field) => fieldKind(field) === 'barcode');
console.info(unsupported.map((field) => field.name));
```

## Form data import and export

| Format | Export | Import |
| --- | --- | --- |
| FDF | `exportFormFdf(fileName?)`: `Uint8Array` | `importFormFdf(bytes)` |
| XFDF, fields only | `exportFormXfdf(fileName?)`: string | `importFormXfdf(xml)` |
| JSON | `exportFormJson({ flat? })`: object | `importFormJson(objectOrString)` |
| XML data | `exportFormXml()`: string | `importFormXml(xml)` |

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

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

const nested = pdf.exportFormJson();
const flat = pdf.exportFormJson({ flat: true });
console.info(nested, flat, pdf.exportFormXml(), pdf.exportFormXfdf('order.pdf'), pdf.exportFormFdf());

const result = pdf.importFormJson({ client: { name: 'Northwind Traders', date: '03/03/2026' }, accept: true });
console.info(result.imported, result.changed, result.unknown);
for (const { name, code, key, params, message } of result.rejected) console.warn(name, code, key, params, message);
```

JSON is nested by the dotted field name (`{ "client": { "name": … } }`) or flat with `flat: true` (`{ "client.name": … }`); both shapes import. A check box is `true` or `false`, a radio group its export value or `null`, a multi-select list an array. XML data follows the Acrobat layout: `<fields>` with one element per name segment, repeated elements for several values, and `xfdf:original` on an element whose field name is not a valid XML name. XFDF nests `<field>` elements; flat names are also read.

Every import returns `{ imported, changed, unknown, rejected }`: the number of values accepted, the names of the fields whose value changed (calculated fields included), the names that match no field, and the rejected entries with `name`, `code`, `key`, `params` and `message`. A value is rejected when it fails the format, range, mask or validation script of its field (`code` as in [Validation](#validation)), when it is not one of the choices (`option`), or when the field is a button, signature or barcode field (`type`). An empty required field is not a reason to reject. Accepted values are applied as one undo step and calculations run, as with `setFormValues`. Read-only fields can be imported.

XML and XFDF are read by the package's own parser. It has no DTD support, so entities declared in a document are never expanded; nesting deeper than 64 levels is ignored and documents above 16 MB are refused with `XmlParseError`.

### Form data in the viewer

The Form fields panel and the menu have **Export form data as FDF**, **XFDF**, **JSON** and **XML**, which download a file named after the document, and **Import form data**, which opens a file picker, detects the format from the content and reports the number of imported values, unknown fields and rejected values.

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

declare const container: HTMLElement;
declare const bytes: Uint8Array;
declare const uploaded: File;
const viewer = createPdfViewer(container, { document: bytes });

const fdf: Uint8Array = viewer.exportFormData('fdf');
const json: string = viewer.exportFormData('json');
viewer.downloadFormData('xfdf');

const result = viewer.importFormData(new Uint8Array(await uploaded.arrayBuffer()));
console.info(result.imported, result.unknown, result.rejected.map((entry) => `${entry.name}: ${entry.key}`));
viewer.importFormData({ client: { name: 'Fabrikam Logistics GmbH' } });
viewer.importFormData(json, 'json');
console.info(fdf.length);
```

`exportFormData(format)` returns bytes for `fdf` and a string for `xfdf`, `json` and `xml`. `importFormData(data, format?)` accepts bytes, a string or a plain object (JSON) and throws a `TypeError` when the format cannot be recognised. `downloadFormData` emits `formDataExport` with `{ format, data, fileName }`.

## Form designer

Turn on `enableFormDesigner: true` to add the **Forms** tool group. Pick a field type (text, checkbox, radio button, drop-down, list or signature) and drag a box on the page. While the tool is active, fields show as outlined boxes that you can drag, resize from the corner, move with the arrow keys (Shift for 10 px steps) and delete with Delete; Enter opens the field in the Form fields panel.

Shift-click or Ctrl-click adds a field to the selection, Shift with a drag on the page selects every field the rectangle touches, and Ctrl+A selects the fields of the page. A click on a field of the selection, or in the field list of the panel, makes it the only selected field.

The Form fields panel shows the properties of the selection. For one field it edits the name, the tooltip, the required and read-only flags, multi-line, comb and maximum length (text), the text alignment, the border and fill colour (each with **None**), the format (number with two decimals, currency, percent or date), the font size (0 sizes the text automatically), multi-select (list), custom values (drop-down) and the options (drop-down and list). For several fields it edits the properties they share. **Duplicate** (Ctrl+D) copies the selection and **Delete field** removes it.

With two or more fields selected the panel adds **Arrange**: align left, right, top or bottom edges, align centres or middles, distribute horizontally or vertically (three fields), and match width, height or size. The first selected field is the reference.

For a text field the panel has a **Calculation** editor: not calculated, sum, product, average, minimum or maximum of the fields picked from a list, or a custom expression. A custom expression shows **Supported expression** or **Unsupported expression** as you type, and an unsupported one is not applied. **Calculation order** lists the calculated fields; reorder them with the buttons, by dragging or with Alt+Arrow Up and Alt+Arrow Down. Every change in the designer is one undo step.

```ts
viewer.addFormField({ name: 'purchaseOrder', type: 'text', pageIndex: 0, rect: [360, 640, 540, 660], isRequired: true });
viewer.addFormField({ name: 'tier', type: 'radio', pageIndex: 0, rect: [360, 610, 374, 624], radioValue: 'Gold' });
viewer.addFormField({ name: 'tier', type: 'radio', pageIndex: 0, rect: [420, 610, 434, 624], radioValue: 'Silver' });
viewer.addFormField({
  name: 'fee.monthly',
  type: 'text',
  pageIndex: 0,
  rect: [360, 580, 460, 598],
  alignment: 'right',
  format: { kind: 'number', decimals: 2, separatorStyle: 0, negativeStyle: 0, currency: '€ ', isCurrencyPrepended: true },
});
viewer.updateFormField('client.name', { rect: [200, 690, 470, 708], tooltip: 'Legal name of the client' });
viewer.removeFormField('services');

viewer.setTool('formField', { field: { type: 'combo', options: ['Monthly', 'Quarterly', 'Annually'] } });
```

### Tab order

With the form designer on, the Form fields panel shows the tab order of the fields on one page: the page of the selected field, or the page in view. Move a field with its **Move earlier** and **Move later** buttons, by dragging it, or with Alt+Arrow Up and Alt+Arrow Down while the row has focus; Arrow Up and Arrow Down move between rows. **Order by rows**, **Order by columns** and **Order by structure** set the order of the whole page. Each change is one undo step, is announced to screen readers, and is saved in the file (`/Tabs` and the order of the widgets) so other PDF applications follow it. The Tab key in the viewer moves through the fields of a page in the same order.

```ts
const { mode, widgets } = viewer.getTabOrder(2);
viewer.setTabOrder(2, 'row');
viewer.setFieldTabOrder(2, [widgets[1].widgetId, widgets[0].widgetId]);
```

`getTabOrder(pageIndex)` returns `{ pageIndex, mode, widgets: [{ widgetId, fieldName, rect }] }` with `mode` `row`, `column`, `structure`, `manual` or `unspecified`. `setFieldTabOrder` puts the listed widgets first, in that order, and switches the page to `manual`. `structure` keeps the stored order, because the package does not read the structure tree. The same three methods exist on a headless document.

Adding a radio field with an existing radio field's name adds a button to that group; any other duplicate name throws. A dotted name such as `fee.monthly` is stored as a field hierarchy. `calculation` and `range` in the field input write the matching Acrobat scripts, so other PDF applications run them too.

### Designer helpers

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

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

const copy = pdf.duplicateField('fee.total', { offset: [0, -24], newName: 'fee.totalCopy' });
pdf.updateFormFields(['client.name', 'client.date'], { isRequired: true, fontSize: 10 });
pdf.alignFields(['client.name', 'client.date', 'fee.monthly'], 'left');
pdf.distributeFields(['client.name', 'client.date', 'fee.monthly'], 'vertical');
pdf.sizeFields(['client.name', 'client.date'], 'both');
pdf.alignFields([{ name: 'billing', widgetIndex: 0 }, { name: 'billing', widgetIndex: 1 }], 'top');

pdf.setFieldCalculation('fee.total', { op: 'product', fields: ['fee.monthly', 'fee.seats'] });
pdf.setFieldCalculation('fee.vat', { expression: 'event.value = Math.round(getField("fee.total").value * 19) / 100;' });
pdf.setCalculationOrder(['fee.total', 'fee.vat']);
console.info(copy?.name, pdf.getCalculationOrder());
```

| Method | Result |
| --- | --- |
| `duplicateField(name, { offset?, pageIndex?, newName? })` | A copy of the field with every widget, moved by `offset` (default `[12, -12]` points) and optionally onto another page. Without `newName` the copy is called `name_copy`, `name_copy2` and so on. Actions other than the format, keystroke, validation and calculation scripts are not copied. |
| `updateFormFields(names, patch)` | The same patch on several fields as one undo step |
| `alignFields(targets, mode)` | `left`, `right`, `top`, `bottom`, `center` (horizontal centres) or `middle` (vertical centres), relative to the first target |
| `distributeFields(targets, direction)` | Equal distances between the centres, `horizontal` or `vertical`; the outermost fields stay in place. Needs three targets. |
| `sizeFields(targets, mode)` | `width`, `height` or `both` of the first target; the top left corner of each field stays in place |
| `getCalculationOrder()`, `setCalculationOrder(names)` | The calculated fields in the order they run, stored in the AcroForm `/CO` array. Calculated fields left out of `names` keep their relative order after the listed ones. |
| `setFieldCalculation(name, calculation)` | `{ op, fields }` with `sum`, `product`, `average`, `min` or `max` writes the standard `AFSimple_Calculate` script. `{ expression }` writes a script from the [safe expression subset](#safe-expression-subset) and throws a `TypeError` for anything else. `null` removes the calculation. |

A target is a field name, which means its first widget, or `{ name, widgetIndex }` for one button of a radio group. Each call is one undo step.

## Fill and sign marks

For a form without fields, **Fill and sign** on the Forms tab places a mark where you click: a tick, a cross, a dot, a circle, today's date or your initials. Choose a mark, click the page once for each mark, and press `Escape` or choose a tool to stop. The viewer asks for the initials the first time and suggests the initials of the current user. To keep them between sessions, store the value of the `fillInitialsChange` event and pass it back as the `fillInitials` option; the viewer then does not ask.

```ts
const viewer = createPdfViewer(document.querySelector('#viewer') as HTMLElement, {
  fillInitials: localStorage.getItem('initials') ?? undefined,
});
viewer.on('fillInitialsChange', ({ initials }) => localStorage.setItem('initials', initials));
```

A mark is written into the page content when it is placed, so it is already flattened: it is part of the page in the saved file and not an annotation. Every mark is one undo step. The Edit images tool selects, moves and deletes the tick, cross, dot and circle, and the Edit text tool the date and the initials; see [Content editing](https://docs.birchui.com/pdf/content-editing.md#in-the-viewer).

From code, `addPageMark(pageIndex, { kind, x, y, size, color })` draws a `tick`, `cross`, `dot` or `circle` centred on a point, and `addPageText` the date or initials.

## Signature fields

An empty signature field shows a **Sign here** button. It opens a dialog with two choices. **Place an electronic signature** opens the signature dialog and places the drawn, typed or uploaded signature inside the field; that is a signature annotation, the field stays unsigned, and the button then reads as "electronic signature placed, not certified". **Sign with a certificate** opens the signing dialog for that field, so the digital signature goes into it; see [Signatures](https://docs.birchui.com/pdf/signatures.md). From code, pass the field name to `signDocument({ field: name, … })`. A field that already holds a digital signature shows who signed it and cannot be signed again.

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

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

for (const field of pdf.getSignatureFields()) {
  console.info(field.name, field.pageIndex, field.rect, field.isSigned, field.isRequired, field.lock);
}
pdf.fillSignatureField('signature', { kind: 'image', image: readImageInfo(scan) });
pdf.fillSignatureField('signature', { kind: 'typed', text: 'Ingrid Solberg' });
```

`getSignatureFields()` lists the signature fields with `name`, `pageIndex`, `rect`, `isSigned` (a digital signature is present), `isRequired`, `isReadOnly` and `lock`, the field's lock dictionary as `{ action: 'all' | 'include' | 'exclude', fields }`. `fillSignatureField(name, signature)` places an electronic signature inside the widget rectangle: an image scaled to fit with its aspect ratio, drawn strokes (`{ kind: 'drawn', inkList }`, scaled to fit) or typed text. It adds a signature annotation marked with `customData.signatureField`, replaces an earlier one for the same field, and creates no digital signature: the field stays unsigned, and the lock is not applied. It throws when the field does not exist or already holds a digital signature.

## Flattening

**Flatten form** in the menu, `viewer.flatten('forms')`, the headless `pdf.flatten('forms')` or `save({ flatten: 'forms' })` draws the current field appearances into the page content and removes the fields, so the values can no longer be changed. Signature fields are kept. The first three are steps in the undo history and change the open document; the save option flattens only the saved copy. See [Saving](https://docs.birchui.com/pdf/saving.md#flattening).

## Detecting fields on a flat form

A scanned or exported form often has blank lines, boxes and tick squares but no fields. With `enableFormDesigner`, **Detect form fields** on the Forms tab proposes fields for the current page and adds them as one undo step; the viewer then switches to the field tool so you can check names and positions. From code:

```ts
const proposed = viewer.detectFormFields([0]);
viewer.addDetectedFields(proposed.filter((field) => field.type === 'text'));
```

`detectFormFields(pageIndexes?)` changes nothing and returns `{ type, pageIndex, rect, name, label, isMultiline, source }` for every proposal; `addDetectedFields(fields?)` adds them (all pages by default). The headless document has the same two methods, and `detectFields` in `@birchui/pdf/engine` works on your own list of shapes and text.

What is recognised, from the vector content and the text of the page:

- a **text field** on a horizontal line at least 36 points long with nothing written on it, in a stroked rectangle 10 to 90 points high with no text inside (multi-line above 30 points), and on a run of four or more underscores in the text;
- a **check box** in an empty square of 6 to 20 points;
- the **name** from the text to the left on the same line (to the right for a check box), else the text above, else the text below, as lower-case words joined by `_` and made unique; a field with no text near gets a numbered name, and the text found is kept as the tooltip.

Not proposed: a rule under a heading, the edges and filled cells of a table, a place that already has a field, and anything on a page that is only an image (run [text recognition](https://docs.birchui.com/pdf/ocr.md) first; lines in a scan are pixels, not paths, and are not detected). Radio groups, drop-down lists, date formats and signature fields are not guessed: a row of choices becomes separate check boxes. On the five flat test forms (23 fields: blank lines, boxes, underscores, choices on one line, two columns) every field is proposed at its place with the expected name and nothing else is proposed; these forms are synthetic and the rules were written against them, so expect misses on forms drawn differently, for example with one path for the whole grid.

## Export

`exportXfdf()` includes field values together with the annotations, and `importXfdf()` fills them. For form data alone, in FDF, XFDF, JSON or XML, see [Form data import and export](#form-data-import-and-export). `getFormValues()` returns a plain object for your own storage.
