---
title: "Filling forms — Angular"
description: "Let people fill in PDF forms, read and set values from your code, check required fields, and move form data in and out."
framework: "Angular"
other_frameworks:
  "React": "https://www.embedpdf.com/docs/headless/react/forms.md"
  "Vue": "https://www.embedpdf.com/docs/headless/vue/forms.md"
  "Svelte": "https://www.embedpdf.com/docs/headless/svelte/forms.md"
source: "https://www.embedpdf.com/docs/headless/angular/forms"
---

# Filling forms

Many PDFs are forms: text boxes, checkboxes, dropdowns, signature fields. Register `withForm()` and
put `<epdf-form-layer>` in each page, and people can fill them in:

**`form-layer.ts`**

```typescript
import { Component } from '@angular/core';
import { EpdfFormLayer, withForm } from '@embedpdf/angular/form';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { provideEmbedPdf } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { engine } from './pdf';

@Component({
  selector: 'app-form-viewer',
  imports: [EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer],
  providers: [provideEmbedPdf({ engine }, withStage(), withRender(), withInteraction(), withForm())],
  template: `
    <epdf-stage>
      <ng-template epdfPage>
        <epdf-render-layer />
        <epdf-form-layer />
      </ng-template>
    </epdf-stage>
  `,
})
export class FormViewer {}
```

**`basic.ts`**

```typescript
import { ChangeDetectionStrategy, Component, inject, ViewEncapsulation } from '@angular/core';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfForm, EpdfFormLayer, withForm } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';

const forms = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/forms.pdf');
  return { kind: 'bytes', id: 'forms', bytes: new Uint8Array(await response.arrayBuffer()) };
};

@Component({
  selector: 'demo-root',
  imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: forms }] },
      withStage(),
      withRender(),
      withInteraction(),
      withForm(),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './basic.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="toolbar">
        <output class="readout">{{ form.fields().length }} fields: click one and fill it in</output>
      </div>
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-form-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  protected readonly form = inject(EpdfForm);
}
```

**`basic.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --canvas: #f7f9fc;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The controls, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
}

.readout {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
}

/* The pages */
.stage {
  height: 440px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

Each field becomes a real HTML control, placed and styled like the field in the PDF: people type in text
boxes, tick checkboxes, pick from lists, and move between fields with Tab. A value is saved into the
document as it's entered, so it's there when the PDF is downloaded, and every PDF app shows it. The
form layer paints the fields as the engine draws them, so while it's on the page, the render layer
leaves them out of the page picture.

## Read the form

`form.fields()` is every field, as a signal: your view updates when a value changes.

**`field-list.ts`**

```typescript
import { Component, inject } from '@angular/core';
import { EpdfForm } from '@embedpdf/angular/form';

@Component({
  selector: 'app-field-list',
  template: `
    <ul>
      @for (field of form.fields(); track field.name) {
        <li>{{ field.name }}: {{ field.kind }}</li>
      }
    </ul>
  `,
})
export class FieldList {
  protected readonly form = inject(EpdfForm);
}
```

Each field has its full `name` (such as `billing.name`), its `kind` (`'text'`, `'checkbox'`,
`'radio'`, `'combobox'`, `'listbox'`, `'pushbutton'` or `'signature'`), its value, and a `ref`: its
address for everything else. The fields and their values are the engine's; see
[Forms](https://www.embedpdf.com/docs/engine/forms.md#read-the-form) for every kind's value.

For one field, such as a total you show in your own UI, use `form.valueOf()`:

**`invoice-total.ts`**

```typescript
import { Component, inject } from '@angular/core';
import { EpdfForm, toFieldRef } from '@embedpdf/angular/form';

@Component({
  selector: 'app-invoice-total',
  template: `
    @let current = total();
    @if (current && 'value' in current) {
      <output>{{ current.value }}</output>
    }
  `,
})
export class InvoiceTotal {
  protected readonly total = inject(EpdfForm).valueOf(toFieldRef('invoice.total'));
}
```

`toFieldRef(name)` makes a ref from a field's full name, for when you know a field by name.

**`read.ts`**

```typescript
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  signal,
  untracked,
  ViewEncapsulation,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfForm, EpdfFormLayer, toFieldRef, withForm } from '@embedpdf/angular/form';
import type { FormField } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';

const forms = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/forms.pdf');
  return { kind: 'bytes', id: 'forms', bytes: new Uint8Array(await response.arrayBuffer()) };
};

/** A field's value as text, whatever its kind. */
function valueText(field: FormField): string {
  switch (field.kind) {
    case 'text':
    case 'combobox':
      return field.value || '—';
    case 'checkbox':
      return field.checked ? 'checked' : 'not checked';
    case 'radio':
      return field.value === 'Off' ? '—' : field.value;
    case 'listbox':
      return field.selectedValues.join(', ') || '—';
    default:
      return '';
  }
}

@Component({
  selector: 'demo-root',
  imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: forms }] },
      withStage(),
      withRender(),
      withInteraction(),
      withForm(),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './read.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="toolbar">
        <output class="readout">Hello, {{ greeting() }}</output>
        @if (changed(); as field) {
          <output class="note">Last change: {{ field }}</output>
        }
      </div>
      <div class="viewer">
        <epdf-stage class="stage">
          <ng-template epdfPage>
            <epdf-render-layer />
            <epdf-form-layer />
          </ng-template>
        </epdf-stage>
        <ul class="fields">
          @for (field of form.fields(); track field.name) {
            <li class="field">
              <span class="field-name">
                {{ field.name }} <span class="kind">{{ field.kind }}</span>
              </span>
              <span class="field-value">{{ valueText(field) }}</span>
            </li>
          }
        </ul>
      </div>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  protected readonly form = inject(EpdfForm);
  private started = false;

  protected readonly valueText = valueText;
  /** One field's value: it changes only when that field does. */
  private readonly name = this.form.valueOf(toFieldRef('name'));
  protected readonly greeting = computed(() => {
    const name = this.name();
    return name && 'value' in name && name.value ? name.value : 'stranger';
  });
  protected readonly changed = signal<string | null>(null);

  constructor() {
    // Every change, whoever made it: typing, a script, or code.
    this.form.valueChanged$
      .pipe(takeUntilDestroyed())
      .subscribe(({ field }) => this.changed.set(field.name));

    // On load: a name filled in.
    effect(() => {
      if (this.form.status() !== 'ready' || this.started) return;
      this.started = true;
      untracked(() => {
        void this.form.setValue(toFieldRef('name'), { value: 'Ada Lovelace' });
      });
    });
  }
}
```

**`read.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --text: #3b4b7a;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --surface: #ffffff;
  --canvas: #f7f9fc;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The greeting, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  gap: 12px;
  margin-bottom: 14px;
}

.readout {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
}

.note {
  font-size: 12px;
  color: var(--muted);
}

/* The pages and the fields: stacked, and side by side where there's room */
.viewer {
  container-type: inline-size;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.stage,
.fields {
  flex: 1 1 100%;
  box-sizing: border-box;
  border: 1px solid var(--line);
  border-radius: 14px;
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.stage {
  height: 340px;
  background: var(--canvas);
}

.fields {
  margin: 0;
  padding: 6px;
  list-style: none;
  background: var(--surface);
}

@container (min-width: 620px) {
  .stage {
    flex: 1 1 0;
    min-width: 0;
    height: 440px;
  }

  .fields {
    flex: 0 0 220px;
    max-height: 440px;
    overflow-y: auto;
  }
}

/* One field: its name and kind, then its value */
.field {
  display: flex;
  flex-direction: column;
  gap: 3px;
  padding: 8px 10px;
  border-radius: 9px;
}

.field + .field {
  border-top: 1px solid var(--line);
}

.field-name {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
}

.kind {
  font-size: 11px;
  font-weight: 500;
  color: var(--muted);
}

.field-value {
  font-size: 13px;
  color: var(--text);
  overflow-wrap: anywhere;
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

## Fill in a field

`setValue()` takes the same values a field reads:

```ts
await form.setValue(name.ref, { value: 'Ada Lovelace' }); // text
await form.setValue(agree.ref, { checked: true }); // checkbox
await form.setValue(plan.ref, { value: 'yearly' }); // radio group: the button's export value
await form.setValue(country.ref, { value: 'NL' }); // dropdown: an option's value
await form.setValue(toppings.ref, { selectedValues: ['cheese', 'olives'] }); // list
```

It runs the same checks and scripts as typing does, and resolves with `{ field, status }`: `status`
is `'applied'`, `'unchanged'`, or `'rejected'` when the form's own validation refused the value.

The field shows the new value at once, before the engine answers, and the promise resolves once it
has. What the form's scripts calculate from it goes with it, as one change: one request, and one
step to undo. The field stays editable meanwhile; filling it in again is the next change. A value
the engine refuses goes back to the one the field had.

Your own inputs can fill in fields too. `form.controlOf(ref)` gives you a field as an Angular
`FormControl`: it holds the field's value, and fills in the field when the control changes, with
the same checks and scripts:

**`form-control.ts`**

```typescript
import { Component, inject } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { EpdfForm, toFieldRef } from '@embedpdf/angular/form';

@Component({
  selector: 'app-billing-name',
  imports: [ReactiveFormsModule],
  template: `
    <label>
      Name
      <input [formControl]="name" />
    </label>
  `,
})
export class BillingName {
  protected readonly name = inject(EpdfForm).controlOf(toFieldRef('billing.name'));
}
```

To fill many fields at once, such as from your backend, pass them by name:

```ts
await form.importValues({ 'billing.name': 'Ada Lovelace', 'billing.country': 'NL', agree: true });
```

`importValues()` and `setValues()` write every value as one change, with the calculations run once
after them. Each field's own keystroke and validation scripts don't run, as when a script sets a
field's `value` in Acrobat.

**`fill.ts`**

```typescript
import {
  ChangeDetectionStrategy,
  Component,
  inject,
  signal,
  ViewEncapsulation,
} from '@angular/core';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfForm, EpdfFormLayer, toFieldRef, withForm } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';

const forms = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/forms.pdf');
  return { kind: 'bytes', id: 'forms', bytes: new Uint8Array(await response.arrayBuffer()) };
};

/** One field of each kind, with `setValue()` in the shape each one takes. */
async function fillIn(form: EpdfForm) {
  await form.setValue(toFieldRef('name'), { value: 'Ada Lovelace' }); // text
  await form.setValue(toFieldRef('updates'), { checked: true }); // checkbox
  await form.setValue(toFieldRef('plan'), { value: 'yearly' }); // radio group: a button's value
  await form.setValue(toFieldRef('framework'), { value: 'React' }); // dropdown: an option's value
  return form.setValue(toFieldRef('topics'), { selectedValues: ['Forms', 'Signatures'] }); // list
}

@Component({
  selector: 'demo-root',
  imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: forms }] },
      withStage(),
      withRender(),
      withInteraction(),
      withForm(),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './fill.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="toolbar">
        <button type="button" class="button" (click)="fillIn()">Fill in</button>
        <button type="button" class="button" (click)="fillFromBackend()">
          Fill from your backend
        </button>
        <button type="button" class="button" (click)="reset()">Reset</button>
        @if (result()) {
          <output class="readout">{{ result() }}</output>
        }
      </div>
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-form-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  private readonly form = inject(EpdfForm);
  protected readonly result = signal('');

  protected async fillIn() {
    const { status } = await fillIn(this.form);
    this.result.set(`Filled in: ${status}`);
  }

  protected async fillFromBackend() {
    // Plain values by full name, as your backend would send them.
    const { applied, skipped } = await this.form.importValues({
      name: 'Grace Hopper',
      framework: 'Vue',
      updates: false,
      topics: ['Annotations'],
      phone: '555-0100',
    });
    this.result.set(`${applied.length} filled, ${skipped.length} skipped`);
  }

  protected async reset() {
    const { fields } = await this.form.reset();
    this.result.set(`${fields.length} fields reset`);
  }
}
```

**`fill.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The controls, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 13px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

.readout {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
}

/* The pages */
.stage {
  height: 440px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

## Image fields

An [image field](https://www.embedpdf.com/docs/headless/angular/forms/building.md#image-fields) holds a picture: initials, a second signature, a
photo. Put a picture in, or take it out:

```ts
await form.setButtonImage(initials.ref, { source: png }); // a PNG, a JPEG or a one-page PDF
await form.setButtonImage(initials.ref, null); // empty again
```

`source` takes what a stamp's does: a `Uint8Array`, a `Blob`, or `{ data, mimeType }`. It
resolves `{ field }`.

- **It's filling in.** It takes what `setValue()` takes, `form.canFill(ref)`, so a signer puts
  pictures into their own image fields and the ones [anyone fills in](#fields-anyone-fills-in).
- **Only an image field takes one.** Any other push button rejects `invalid-input`, a button
  that only shows a picture, such as a logo, among them: nobody fills that in.
- **One change, one step to undo.** The box says it holds a picture (`empty` is `false`) at once,
  and the picture shows once the engine has drawn it. Cancelled with its `signal` while the
  picture loads, it writes nothing.
- **An empty one is empty.** A required image field is on the list of
  [what's still to fill in](#check-required-fields) until it holds a picture.
- **`prefill()` leaves it alone:** the app knows no picture for a purpose.
- **Signing locks it** once it holds a picture, as it locks a filled-in text field: a field
  anyone fills in, filled by one signer, is locked by their signature.

With the [signature plugin](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#sign-here-in-a-form), pressing an empty or a filled
image field makes it the target, as pressing a signature field does. Your card puts the
person's mark in with `signature.placeMark(mark, { field })`, which always puts a mark into an
image field as its picture: it never signs it. An armed mark
[clicked on the field](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#let-people-click-to-sign) goes in the same way. Without
the signature plugin, the press does nothing, and your own UI calls `setButtonImage()`.

## Check required fields

A form marks some fields as required. Check them before you submit or download:

```ts
const { valid, missing, required } = form.validate();
if (!valid) form.focus(missing[0].ref);
```

`missing` lists the required fields that are empty, in page order, so you can take the user to the
first one: `focus()` brings it into view and puts the cursor in it. `required` lists every required
field the user fills in, empty or not, in the same order, so "2 of 5" is
`required.length - missing.length` of `required.length`.

Only the user's own fields count: the ones they may fill in, and the signature fields they may
sign. Another signer's are theirs. A field a [signature has locked](#signed-documents) is no
longer anyone's to fill in, so it leaves both lists: after a signer signs, the count is of what
is still open. A [`date-signed`](https://www.embedpdf.com/docs/headless/angular/forms/building.md#what-a-field-is-for) field never counts: nobody
types the day of signing, so nobody is asked for it.

A field is filled in when it holds what it asks for:

| Field                 | Filled in when                        |
| :-------------------- | :------------------------------------ |
| Text box, dropdown    | It has text                           |
| Checkbox, radio group | One is on                             |
| List                  | Something is selected                 |
| Image field           | It has a picture                      |
| Signature field       | It's signed, or a mark is drawn in it |

A signature field counts with a mark alone. So a form whose signatures are
[drawn in without signing](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#fill-a-field-without-signing) can be completed, and
taking the mark out makes the field empty again.

To show people what the form still asks for, give `fields.required` a color: each required field
of the user's that is still empty then has an edge in it, until it's filled in. It's off at
first. Screen readers hear that a text box, a checkbox, a dropdown or a list is required either
way; see [Screen readers](#screen-readers).

**`validate.ts`**

```typescript
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  untracked,
  viewChild,
  ViewEncapsulation,
} from '@angular/core';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfForm, EpdfFormLayer, toFieldRef, withForm } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';

const forms = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/forms.pdf');
  return { kind: 'bytes', id: 'forms', bytes: new Uint8Array(await response.arrayBuffer()) };
};

@Component({
  selector: 'demo-root',
  imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: forms }] },
      withStage(),
      withRender(),
      withInteraction(),
      // A required field that is still empty has an edge in this color.
      withForm({ fields: { required: '#b45309' } }),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './validate.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="toolbar">
        <button type="button" class="button" (click)="submit()">Submit</button>
        <output class="readout" [class.missing]="!check().valid">
          {{ check().required.length - check().missing.length }} of
          {{ check().required.length }} required fields filled in
        </output>
      </div>
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-form-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  private readonly form = inject(EpdfForm);
  private readonly stage = viewChild(EpdfStage);
  private started = false;

  /** The required fields, and the ones still empty. */
  protected readonly check = computed(() => {
    this.form.fields(); // again when a field is filled in
    return this.form.validate();
  });

  constructor() {
    // Fill in a name once the form is read, so one of its required fields is done.
    effect(() => {
      if (this.form.status() !== 'ready' || !this.stage() || this.started) return;
      this.started = true;
      untracked(() => {
        void this.form.setValue(toFieldRef('name'), { value: 'Ada Lovelace' });
      });
    });
  }

  /** Submit: put the cursor in the first field the form still asks for. */
  protected submit() {
    const first = this.check().missing[0];
    if (first) this.form.focus(first.ref);
  }
}
```

**`validate.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --warn: #b45309;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The controls, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 13px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

.readout {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
}

.missing {
  color: var(--warn);
}

/* The pages */
.stage {
  height: 440px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

> **Try it:** the form asks for three fields, and the name is filled in, so the bar says 1 of 3.
> The two it still asks for have an orange edge. Press **Submit**: the cursor goes to the first
> of them. Type an email address and press Tab: its edge goes, and the bar says 2 of 3.

### Check the values too

A value is checked against the form's own rules when it's entered; see
[Calculations, formatting and validation](#calculations-formatting-and-validation). A value that
got there another way wasn't: one that `importValues()` or `setValues()` wrote, one that came
with the file, one written while `validation` was `'none'`, or one whose rule reads a field that
changed since. Before you submit, check them all:

```ts
const { valid, missing, invalid } = await form.validateValues();
if (!valid) form.focus((missing[0] ?? invalid[0].field).ref);
```

`validateValues()` resolves what `validate()` returns, and `invalid`: the user's fields whose
value a rule refuses, in page order, each as `{ field, message }`. `valid` is `true` when
`missing` and `invalid` are both empty.

- **It runs each field's own rules on the value it holds:** its keystroke and validation
  scripts, as entering that value would. A date or a time is checked against its
  [pattern](#dates).
- **It writes nothing.** No value changes, nothing is calculated or formatted, no alert reaches
  your UI, and `validationRejected$` doesn't fire.
- **It leaves the scripts as they are.** The rules run in a scripts engine started for the check
  and thrown away after it, with the values the form holds now and a fresh copy of the functions
  and variables the document defines for all its fields. So a check never changes what the next
  edit is told, and its own answer doesn't depend on the checks and the edits before it: what a
  script changed in a variable earlier in the session isn't there for the check. A rule that
  reads the clock can still answer differently later. The fields are checked in page order in
  that one engine, so a rule sees what the rule of a field before it left there.
- **It never calls a form valid that it couldn't check.** When the form's fields couldn't be
  read, or the last read of them failed, it reads them again, and rejects with that read's error
  when it fails too. It rejects as well when a script can't run to its end.
- **`message` is the rule's own:** what its script would say in an alert, such as "Invalid
  date/time: please ensure that the date/time exists". It's `null` for a rule that refuses
  without a word.
- **An empty field breaks no rule.** Whether it must have a value is `missing`.
- **The `validation` setting doesn't change it.** The setting says what a write runs; this is
  the check you ask for.
- **The scripts need JavaScript on** in the [actions plugin](https://www.embedpdf.com/docs/headless/angular/documents/actions.md). Without it,
  only dates and times are checked.
- **The day of signing is never listed,** as in `validate()`.

`validate()` stays the instant check: it answers at once, from what the form shows.
`validateValues()` waits for the values on their way to be written first. Its whole answer is of
one form, the one shown when its turn came: a value changed while the rules run is no part of it.

**`validate-values.ts`**

```typescript
import {
  ChangeDetectionStrategy,
  Component,
  inject,
  signal,
  ViewEncapsulation,
} from '@angular/core';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { withActions } from '@embedpdf/angular/actions';
import { EpdfForm, EpdfFormLayer, withForm } from '@embedpdf/angular/form';
import type { FormValuesValidation } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';

const invoice = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/invoice.pdf');
  return { kind: 'bytes', id: 'invoice', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// An order as a backend might send it: a quantity that is no number, a date that is no date.
const ORDER = { 'billing.name': 'Ada Lovelace', 'invoice.license.qty': 'two', date: 'next week' };

@Component({
  selector: 'demo-root',
  imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: invoice }] },
      withStage(),
      withRender(),
      withInteraction(),
      withForm(),
      // The form's own rules are scripts: they run with JavaScript on in the actions plugin.
      withActions({ javascript: { enabled: true } }),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './validate-values.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="toolbar">
        <button type="button" class="button" (click)="importOrder()">Import an order</button>
        <button type="button" class="button" (click)="checkValues()">Check the values</button>
      </div>
      @if (check(); as check) {
        @if (check.valid) {
          <output class="readout passed">Every value passes its field’s rules</output>
        } @else {
          <ul class="problems">
            @for (field of check.missing; track field.name) {
              <li>
                <b>{{ field.name }}</b
                >: the form asks for a value
              </li>
            }
            @for (problem of check.invalid; track problem.field.name) {
              <li>
                <b>{{ problem.field.name }}</b
                >: {{ problem.message ?? 'its rule refuses the value' }}
              </li>
            }
          </ul>
        }
      } @else {
        <output class="readout">Not checked yet</output>
      }
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-form-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  private readonly form = inject(EpdfForm);
  protected readonly check = signal<FormValuesValidation | null>(null);

  /** importValues() writes the values as one change. It runs no field's own rule. */
  protected async importOrder() {
    await this.form.importValues(ORDER);
    this.check.set(null);
  }

  /** Check every value against its field's own rules, and go to the first problem. */
  protected async checkValues() {
    const result = await this.form.validateValues();
    this.check.set(result);
    const first = result.missing[0] ?? result.invalid[0]?.field;
    if (first) this.form.focus(first.ref);
  }
}
```

**`validate-values.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --refused: #b42318;
  --passed: #15803d;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The buttons, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 13px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

/* What the check found, under the buttons */
.readout {
  display: block;
  margin: 0 0 12px;
  font-size: 13px;
  font-weight: 600;
  color: var(--muted);
}

.readout.passed {
  color: var(--passed);
}

.problems {
  margin: 0 0 12px;
  padding: 0;
  list-style: none;
  font-size: 12.5px;
  line-height: 1.45;
  color: var(--refused);
}

.problems b {
  font-weight: 650;
}

/* The pages */
.stage {
  height: 440px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

> **Try it:** press **Import an order**. It writes three values with `importValues()`, which
> runs no field's own rule, so the form now holds a quantity that is no number and a date that is
> no date. Press **Check the values**: both are listed, each with what its rule says. Correct one
> in the form and check again.

## Move between fields

Tab and Shift+Tab move through the fields in the document's order, from page to page, including
pages that aren't on screen: the view follows the field. On each page the fields come in the order
the PDF gives: as its tags read (most tagged forms say so), by rows, by columns or as they were added.
See [Keyboard order](https://www.embedpdf.com/docs/engine/documents/pages.md#keyboard-order). Fields the user can't fill in are skipped,
and a group of radio buttons is one stop, whose buttons the arrow keys move between. Tab on the last
field, or Shift+Tab on the first, leaves the form, as it does on a web page.

A signature field is a stop when something can sign it: the signature plugin makes it a button
(see ["Sign here" in a form](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#sign-here-in-a-form)), or a
[control of your own](https://www.embedpdf.com/docs/headless/angular/forms/controls.md) draws it. With neither, the field is only its picture, and
the cursor passes over it.

The field the cursor is in shows a ring in the form's [`focus.color`](#settings), whatever its
kind: a text box, a checkbox, a radio button, a dropdown, a list, a push button, an image field
or a signature field. It shows however the cursor got there, by Tab, `focus()`, `focusNext()` or
a press, and the browser's own focus outline never shows on a field. A press puts the cursor in
the field in every browser: Safari gives a pressed button no focus of its own, so the layer puts
it there.

Your code moves the cursor too. `focus(ref)` brings a field into view, on whatever page it is, and
puts the cursor in it; `focusNext()` goes on from the field the cursor is in, or was in last:

```ts
form.focus(email.ref); // the cursor in a field
form.focus(email.ref, { select: true }); // with its text selected, so typing replaces it
form.focusNext(); // the next field, as Tab does
form.focusNext({ backward: true }); // the one before
form.focusNext({ empty: true, wrap: true }); // the next empty field, starting over at the end
form.focusNext({ required: true, empty: true }); // the next one the form still asks for
```

`required: true` goes only to the fields `validate()` counts as required, and `empty: true` only
to the ones that hold nothing yet, by the same rule: a signature field with a mark drawn in it
is passed over.

Both return `false` when there is no such field, none the user can fill in, or none with anything
to put the cursor in. A field takes the cursor as soon as it's on screen; on iPhone and iPad, the
keyboard opens for a field that was already showing, and one that had to come into view opens it on
a tap.

`form.focusedField()` is the field the cursor is in, or `null`, and
`focusChanged$` tells you each time it moves, for a help text next to the
form or a step counter.

## Calculations, formatting and validation

Many forms add up totals, format dates and check values with scripts. With JavaScript on in the
[actions plugin](https://www.embedpdf.com/docs/headless/angular/documents/actions.md), they run as people type, as in Acrobat:

**`scripts.ts`**

```typescript
import { Component } from '@angular/core';
import { withActions } from '@embedpdf/angular/actions';
import { withForm } from '@embedpdf/angular/form';
import { provideEmbedPdf } from '@embedpdf/angular/runtime';
import { engine } from './pdf';

@Component({
  selector: 'app-form-viewer',
  providers: [
    provideEmbedPdf({ engine }, /* … */ withForm(), withActions({ javascript: { enabled: true } })),
  ],
  template: `<!-- … -->`,
})
export class FormViewer {}
```

When a script refuses a value, such as a date in the wrong format, the field keeps its old value,
the box keeps what was typed so it can be corrected, as in Acrobat, and
`validationRejected$` tells you why, so you can show a message.

**`scripts.ts`**

```typescript
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  signal,
  ViewEncapsulation,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { withActions } from '@embedpdf/angular/actions';
import { EpdfForm, EpdfFormLayer, toFieldRef, withForm } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';

const invoice = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/invoice.pdf');
  return { kind: 'bytes', id: 'invoice', bytes: new Uint8Array(await response.arrayBuffer()) };
};

@Component({
  selector: 'demo-root',
  imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: invoice }] },
      withStage(),
      withRender(),
      withInteraction(),
      withForm(),
      // The form's scripts run with JavaScript on in the actions plugin.
      withActions({ javascript: { enabled: true } }),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './scripts.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <!-- The amounts and the total are calculated by the form's scripts. -->
      <div class="toolbar">
        <output class="readout">Total: {{ totalText() }}</output>
        @if (refused(); as refused) {
          <output class="refused">{{ refused }}</output>
        }
      </div>
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-form-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  private readonly form = inject(EpdfForm);

  private readonly total = this.form.valueOf(toFieldRef('invoice.total'));
  protected readonly totalText = computed(() => {
    const total = this.total();
    return total && 'value' in total && total.value ? total.value : 'type a quantity';
  });
  protected readonly refused = signal<string | null>(null);

  constructor() {
    // A script refused a value, such as a date that isn't day/month/year.
    this.form.validationRejected$
      .pipe(takeUntilDestroyed())
      .subscribe(({ field, issues }) =>
        this.refused.set(`${field.name}: ${issues[0]?.message ?? 'refused'}`),
      );
  }
}
```

**`scripts.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --canvas: #f7f9fc;
  --shadow: rgb(7 32 76 / 0.04);
  --refused: #b42318;
}

/* The total and the last refused value, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  gap: 12px;
  margin-bottom: 14px;
}

.readout {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
}

.refused {
  font-size: 12.5px;
  color: var(--refused);
}

/* The pages */
.stage {
  height: 440px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

The scripts read the form as the user sees it, values still on their way included, so nothing is
read from the engine for them. Their engine starts when the first field of a form with scripts takes
focus, so the first value doesn't wait for it; a form without scripts never starts it.

## Dates

A text field or a dropdown can say what shape its value has: its `format`. A date field is a text
field with a date format, and a pattern such as `dd/mm/yyyy`:

```ts
const start = form.get(toFieldRef('start'));
if (start?.kind === 'text') {
  start.format; // { kind: 'date', pattern: 'dd/mm/yyyy' }
}
```

In the PDF that is Acrobat's own date format. So a date field made in Acrobat is one here, and
Acrobat shows its date picker on one made here. A format is one of these:

- **`{ kind: 'date', pattern }` or `{ kind: 'time', pattern }`:** a date or a time, written the
  way the [pattern](https://www.embedpdf.com/docs/engine/forms/authoring.md#patterns) says.
- **`{ kind: 'other' }`:** a format only the PDF's own script knows, such as a number format.
- **`null`:** none. Any text goes.

What people type into a date or a time field is checked against its pattern, and shown the way
the pattern writes it: `5/3/26` in a `dd/mm/yyyy` field shows as `05/03/2026`. Text that is no
date is refused like any value the form refuses: the field keeps its old value, and
`validationRejected$` fires.

This works with JavaScript on or off. With it on, the field's own scripts do it. With it off, the
form plugin checks and writes the date itself, with the same code those scripts run, so the PDF
holds the same text either way. An `'other'` format needs its script: with JavaScript off, such a
field takes any text.

A dropdown with a date or a time format is checked the same way. What is checked, and shown the
way the pattern writes it, is what the dropdown shows: the label of the option that is chosen,
or the text itself where it's none of the options (an editable dropdown takes such text). The
field keeps the value the option exports. With JavaScript on, the form plugin makes
this check itself too, where the dropdown's keystroke script is the one its format goes with,
as it is for a format set here or in Acrobat: a dropdown's keystroke script is not run. A
dropdown whose PDF only has the script that shows a date, and none that checks one, takes any
text with JavaScript on.

For a date picker of your own, `formatDate()` writes a date the way a pattern asks, and
`parseDate()` reads one back:

```ts
const today = { year: 2026, month: 11, day: 24 };

formatDate(today, 'dd/mm/yyyy'); // '24/11/2026'
parseDate('5/3/26', 'dd/mm/yyyy', today);
// { year: 2026, month: 3, day: 5, hour: 0, … }
parseDate('soon', 'dd/mm/yyyy', today); // null
```

Both come from the same import as `EpdfForm`. A date is its parts as the field shows them, with no
time zone, and `today` fills in what the text leaves out.
[Show a calendar next to a date field](https://www.embedpdf.com/docs/headless/angular/forms/controls.md#show-a-calendar-next-to-a-date-field) puts
them to work, and a field gets its format when the form is
[built](https://www.embedpdf.com/docs/headless/angular/forms/building.md#change-a-fields-settings).

## A field's look and its tint

A field shows in two layers, one over the other.

- **Its look is in the PDF:** its border, its background and the color of its text. Every PDF
  app shows it, and it prints.
- **Its tint is the viewer's,** a light fill and an edge over the look, never saved. It says
  which fields are the user's to fill in. A field's tint is its
  [group's color](#fields-for-several-people). A field [anyone fills in](#fields-anyone-fills-in)
  takes `fields.anyoneTintColor`, a cyan at first. A field in no group takes
  `fields.tintColor` when you give one; it's `null` at first, so such a field has no tint.

While a user fills in the form, the viewer paints only the fields they fill in: the tint, an
edge in `fields.border` on a field with no border of its own and no tint,
[what an empty field shows](https://www.embedpdf.com/docs/headless/angular/forms/controls.md#placeholders), and, once `fields.required` has a
color, an edge in it on a [required field that is still empty](#check-required-fields). Every
other field looks as the PDF
has it and takes no input: another person's, a read-only one, a signature field that's signed,
the date of signing, which the Date signed tool makes read-only, and a field a signature locked,
whoever signed. So does every field `fillable` leaves out. In
[design mode](https://www.embedpdf.com/docs/headless/angular/forms/building.md#place-fields-for-a-signer) every field shows: in its tint, else with
the `fields.border` edge, so a field with no look of its own shows too. How strongly a tint shows
is `fields.tint`, and `0` turns tints off.

## Fields for several people

When a form goes to several people, each fills in their own fields: a field can be in a
[group](https://www.embedpdf.com/docs/engine/forms/groups.md), and a user's permissions name the groups they fill in. The form
layer shows whose field is whose, each group in a color of its own, with nothing to set up.

The PDF holds only each field's group id. Who a group is belongs to your app, and it changes from
one document to the next, so you tell each open document:

```ts
form.setGroups([
  { id: 'buyer', label: 'Dana Smith', color: '#2563eb' },
  { id: 'seller', label: 'Lanternfield' }, // a color is picked for it
]);
```

Call it where the document shows, so every document you open gets its own list:

**`name-groups.ts`**

```typescript
import { Component, effect, inject, input } from '@angular/core';
import { EpdfForm, type FormGroupInput } from '@embedpdf/angular/form';

/** Render it where the document shows, so every document you open gets its own list. */
@Component({ selector: 'app-signers', template: '' })
export class Signers {
  readonly signers = input.required<FormGroupInput[]>();

  private readonly form = inject(EpdfForm);

  constructor() {
    effect(() => this.form.setGroups(this.signers()));
  }
}
```

- **The fields a user may fill in show in their group's color:** a light fill and an edge. Other
  people's fields show as the PDF has them, and take no input. So does a field that takes no value
  any more: a read-only one, or a signature field that's signed. In
  [design mode](https://www.embedpdf.com/docs/headless/angular/forms/building.md#place-fields-for-a-signer) every field shows its group's color.
- **`label` is who the group is, for people.** Screen readers read it after the field's name,
  "Signature, Dana Smith", on the user's own fields and on other people's.
- **`color` is a CSS color,** so it can name a variable of yours: `color: 'var(--signer-1)'`.
  Without one, a group gets one of eight colors by its place in the list, so the first eight
  never share one.
- **`setGroups()` takes the whole list,** and an empty one clears it. Call it again when your
  list changes; the same list again changes nothing. Naming a group needs no permission, so a
  signer's page names them too.
- **Each open document has its own list.** The same id can be one person in this document and
  another in the next.
- **A group you don't name shows too,** in one of the eight colors and with no name. A field in no
  group takes `fields.tintColor`, when you give one.
- **A field anyone fills in is every signer's,** in a color of its own. See
  [Fields anyone fills in](#fields-anyone-fills-in).

For a legend of your own, `form.groups()` in the form's [state](#state) has every group you named, in your order, then
every other group the form's fields are in, each as `{ id, label, color }`. A group you didn't
name has `null` for its label. `form.listGroups()` reads the same list once.

Two pages show a group in the same color when they name the same groups in the same order, so
give the sender's page and each signer's the same list. For a color that never depends on the
order, give each group its own.

Names and colors stay in your app, never in the PDF. How strongly the fill shows is
`fields.tint`, and `0` turns the colors off; see [Settings](#settings).
[Place fields for a signer](https://www.embedpdf.com/docs/headless/angular/forms/building.md#place-fields-for-a-signer) has a live example.

### Fields anyone fills in

A field can be for no one signer: a date either party may settle, a note anyone may add. It's
[for anyone](https://www.embedpdf.com/docs/engine/forms/groups.md#fields-anyone-fills-in) (its `assignment` is `{ kind: 'anyone' }`), in no group,
and every user who may fill in some field fills it in: each signer, and the sender.

- **It's every signer's to fill in,** so it shows on every signer's page in
  `fields.anyoneTintColor`, a cyan at first. `null` gives it `fields.tintColor`, and
  `--epdf-form-field-anyone-tint-color` wins over the setting.
- **Screen readers read "Anyone" after its name,** in the viewer's language, where a group's
  field reads its group's label: "Return by, Anyone". `listGroups()` and `groups` stay the
  groups alone; put "Anyone" in your legend yourself.
- **Once filled in and signed, it's locked.** Signing locks every field anyone fills in that
  holds a value, so the next signer sees it as the PDF has it. An empty one stays open for the
  next signer. See [Signing](https://www.embedpdf.com/docs/engine/forms/groups.md#signing).
- **A required one is on every signer's list** of [what's still to fill in](#check-required-fields)
  until someone fills it in.
- **`prefill()` leaves it alone:** a name, an address or a date is one signer's.

[Place fields anyone fills in](https://www.embedpdf.com/docs/headless/angular/forms/building.md#place-fields-anyone-fills-in) shows how to make one.

## Values the app already knows

A field can say what it's for: a name, an email address, the day of signing. That is its
`purpose`, set when the form is [built](https://www.embedpdf.com/docs/headless/angular/forms/building.md#what-a-field-is-for). For five purposes
your app already has the answer, four of them in the user's
[identity](https://www.embedpdf.com/docs/headless/angular/concepts/permissions.md#where-the-limits-come-from):

- **`name`** is filled in with the identity's `displayName`.
- **`email`** with its `email`.
- **`organization`** with its `organization`.
- **`organization-title`** with its `title`.
- **`date-signed`** with today's date, on the person's own device, in the field's date pattern,
  else `yyyy-mm-dd`.

`prefill()` writes them into the user's empty fields:

```ts
const { applied, skipped } = await form.prefill();
```

Call it when the person starts filling in, usually right after the document opens:

**`prefill.ts`**

```typescript
import { Component, inject } from '@angular/core';
import { EpdfForm } from '@embedpdf/angular/form';

/** Render it where the document shows: it fills in what the app knows when the person starts. */
@Component({ selector: 'app-prefill', template: '' })
export class Prefill {
  constructor() {
    // A field that has a value is left alone, so a second call writes nothing.
    void inject(EpdfForm).prefill();
  }
}
```

From then on they are values like any other. People see them, and change them unless the field
is read-only.

- **It is one change:** one request, and one step to undo.
- **Only the user's own fields.** A field they may not fill in is another person's, and is left
  for them. So is a field [anyone fills in](#fields-anyone-fills-in): the first signer to open
  the document would put their name there for everyone.
- **A field that has a value is left alone,** whoever wrote it. So calling `prefill()` twice
  writes nothing the second time.
- **A read-only field is filled in too.** Read-only stops people from typing, not your code: make
  a name field read-only when the signer shouldn't change the name you know.
- **The date is written, never asked.** A `date-signed` field is read-only, shows the date as
  text, and says "Filled in when you sign" as its tooltip. It is never on the list of
  [what's still to fill in](#check-required-fields), required or not.
- **A date already written stays,** as any value does: a person who comes back on a later day
  keeps the date `prefill()` wrote the first time. When they sign as their last step, the
  signature plugin's [`finish()`](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#sign-as-the-last-step) writes the day they
  sign over it, right before it signs.
- **Neither is a purpose of your own.** Any word is a purpose, and the field keeps it, but the
  viewer has no value for a word it doesn't know. Write that field yourself, with `setValue()`.

It resolves `{ applied, skipped, failed }`, as `setValues()` does. `applied` has the fields it
wrote. `skipped` has the ones it left, each as `{ ref, reason }`: `'filled'` for a field that has
a value, `'no-value'` when the app has nothing for its purpose, such as an identity without an
email address, and `'for-anyone'` for a field anyone fills in.

**`purposes.ts`**

```typescript
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  input,
  signal,
  ViewEncapsulation,
} from '@angular/core';
import {
  EpdfDocument,
  EpdfDocumentGate,
  EpdfDocuments,
  EpdfViewer,
  provideEmbedPdf,
} from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { EpdfInteraction, withInteraction } from '@embedpdf/angular/interaction';
import { EpdfAnnotationLayer, withAnnotation } from '@embedpdf/angular/annotation';
import { EpdfForm, EpdfFormLayer, withForm } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';

const engine = localEngine();

const loan = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/loan.pdf');
  return { kind: 'bytes', id: 'loan', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// Who the document's groups are: your app's own list. The PDF holds only each field's group id.
const signers = [
  { id: 'borrower', label: 'Dana Smith', color: '#2563eb' },
  { id: 'approver', label: 'Ada Lovelace' }, // a color is picked for it
];

// The sender places fields for both signers. Each signer fills in and signs their own, and your
// app knows who each of them is.
const see = ['doc.open', 'doc.render', 'doc.download', 'doc.forms.read'];
const people = {
  sender: {
    name: 'The sender',
    scope: [
      ...see,
      'doc.forms.modify',
      'fields:set-group:group=borrower',
      'fields:set-group:group=approver',
    ],
    identity: null,
  },
  borrower: {
    name: 'Dana Smith',
    scope: [...see, 'fields:fill:group=borrower', 'fields:sign:group=borrower'],
    identity: {
      userId: 'u_381',
      displayName: 'Dana Smith',
      email: 'dana@fernquill.example',
      organization: 'Fernquill Ltd',
      title: 'Operations',
    },
  },
  approver: {
    name: 'Ada Lovelace',
    scope: [...see, 'fields:fill:group=approver', 'fields:sign:group=approver'],
    identity: {
      userId: 'u_412',
      displayName: 'Ada Lovelace',
      email: 'ada@fernquill.example',
      organization: 'Fernquill Ltd',
      title: 'Finance',
    },
  },
};
type Person = keyof typeof people;

// A signing tool for each kind of value: a text box that says what it is for.
const VALUE_TOOLS = [
  ['signer-name', 'Name'],
  ['signer-email', 'Email'],
  ['signer-organization', 'Organization'],
  ['signer-organization-title', 'Title'],
  ['signer-date-signed', 'Date signed'],
] as const;

/** The sender picks who the next field is for and what it is for, and clicks the page. */
@Component({
  selector: 'demo-sender-toolbar',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="toolbar">
      <span class="label">Next field is for</span>
      @for (group of form.groups(); track group.id) {
        <button
          type="button"
          class="button"
          [attr.aria-pressed]="form.designGroup() === group.id"
          [disabled]="!form.canSetGroup(group.id)"
          (click)="form.setDesignGroup(group.id)"
        >
          <i class="swatch" [style.background]="group.color"></i>{{ group.label ?? group.id }}
        </button>
      }
      <span class="divider"></span>
      @for (tool of tools; track tool[0]) {
        <button
          type="button"
          class="button"
          [attr.aria-pressed]="interaction.activeToolId() === tool[0]"
          (click)="interaction.activateTool(tool[0])"
        >
          {{ tool[1] }}
        </button>
      }
    </div>
  `,
})
export class SenderToolbar {
  protected readonly form = inject(EpdfForm);
  protected readonly interaction = inject(EpdfInteraction);
  protected readonly tools = VALUE_TOOLS;

  constructor() {
    // Start by placing name fields for the first signer.
    this.form.setDesignGroup('borrower');
    this.interaction.activateTool('signer-name');
  }
}

/** A signer starts: the app fills in what it knows about them, in their own fields, as one change. */
@Component({
  selector: 'demo-signer-bar',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="toolbar">
      <output class="readout">{{ message() }}</output>
    </div>
  `,
})
export class SignerBar {
  readonly person = input.required<Person>();

  private readonly filled = signal<number | null>(null);
  protected readonly message = computed(() => {
    const filled = this.filled();
    return filled === null
      ? 'Filling in what the app knows…'
      : `Filled in for ${people[this.person()].name}: ${filled} ${filled === 1 ? 'field' : 'fields'}`;
  });

  constructor() {
    // Another signer's field is left for them, and so is a field that has a value.
    void inject(EpdfForm)
      .prefill()
      .then(({ applied }) => this.filled.set(applied.length));
  }
}

/** Names the open document's groups, and shows the sender's toolbar or a signer's bar. */
@Component({
  selector: 'demo-toolbar',
  imports: [SenderToolbar, SignerBar],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <!-- The open document says what its user may do: it is the sender's while they may
         design it. -->
    @if (form.canDesign()) {
      <demo-sender-toolbar />
    } @else {
      <demo-signer-bar [person]="person()" />
    }
  `,
})
export class Toolbar {
  readonly person = input.required<Person>();

  protected readonly form = inject(EpdfForm);

  constructor() {
    // Tell the open document who its groups are.
    this.form.setGroups(signers);
  }
}

@Component({
  selector: 'demo-root',
  imports: [
    EpdfDocumentGate,
    EpdfStage,
    EpdfPageTemplate,
    EpdfRenderLayer,
    EpdfAnnotationLayer,
    EpdfFormLayer,
    Toolbar,
  ],
  providers: [
    provideEmbedPdf(
      {
        engine,
        scope: people.sender.scope,
        identity: people.sender.identity,
        initialDocuments: [{ source: loan, name: 'equipment-loan.pdf' }],
      },
      withStage(),
      withRender(),
      withInteraction(),
      withAnnotation(),
      withForm(),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './purposes.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <div class="toolbar">
      <span class="label">Open the form as</span>
      <div class="segments">
        @for (each of everyone; track each) {
          <button
            type="button"
            class="segment"
            [attr.aria-pressed]="person() === each"
            (click)="handOver(each)"
          >
            {{ people[each].name }}
          </button>
        }
      </div>
    </div>
    <ng-container *epdfDocumentGate="let document; fallback: opening">
      <demo-toolbar [person]="person()" />
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-annotation-layer />
          <epdf-form-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #opening><p class="loading">Opening…</p></ng-template>
  `,
})
export class App {
  private readonly viewer = inject(EpdfViewer);
  private readonly documents = inject(EpdfDocuments);
  private readonly document = inject(EpdfDocument);
  protected readonly people = people;
  protected readonly everyone = Object.keys(people) as Person[];
  protected readonly person = signal<Person>('sender');

  // A document keeps who it opened for, so the next person opens the saved form again.
  protected async handOver(person: Person) {
    if (person === this.person()) return;
    this.person.set(person);
    const { scope, identity } = people[person];
    this.viewer.updateSettings({ scope, identity });
    const id = this.document.id();
    if (!id) return;
    const bytes = await this.documents.download();
    await this.documents.close(id);
    await this.documents.open({ kind: 'bytes', bytes }, { name: 'equipment-loan.pdf' });
  }
}
```

**`purposes.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --accent: #054fb3;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The controls, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 13px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

.button[aria-pressed='true'] {
  color: var(--accent);
  background: var(--tint);
  border-color: var(--line-strong);
}

/* Who the form is opened as: one of the three */
.segments {
  display: inline-flex;
  gap: 2px;
  padding: 3px;
  background: var(--tint);
  border: 1px solid var(--line);
  border-radius: 10px;
}

.segment {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--muted);
  background: transparent;
  border: 0;
  border-radius: 7px;
  padding: 7px 12px;
  cursor: pointer;
}

.segment:hover {
  color: var(--ink);
}

.segment[aria-pressed='true'] {
  color: var(--accent);
  background: var(--surface);
  box-shadow: 0 1px 3px rgb(7 32 76 / 0.12);
}

.segment:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 1px;
}

/* What the bar says beside its buttons */
.label {
  font-size: 13px;
  font-weight: 600;
  color: var(--muted);
}

/* Who a field is for: a signer's color, beside their name */
.swatch {
  display: inline-block;
  width: 10px;
  height: 10px;
  margin-right: 6px;
  border-radius: 3px;
}

.divider {
  width: 1px;
  height: 20px;
  background: var(--line);
}

.readout {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
}

/* The pages */
.stage {
  height: 440px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

> **Try it:** as the sender, click the borrower's Name box to place a name field for Dana, then
> pick **Date signed** and click the Date box under it. Pick **Ada Lovelace** and **Name**, and
> click the Name box under "Approved by". Each empty field shows what it's for. Open the form as
> **Dana Smith**: her name and today's date are filled in, and Ada's
> field is left for Ada. Open it as **Ada Lovelace**: her name is filled in now, and Dana's field
> holds what Dana left.

## Reset the form

```ts
await form.reset(); // every field the user may fill in, back to its default
await form.reset([name.ref, email.ref]); // some fields
```

## Move form data in and out

For your own backend, plain values are simplest:

```ts
const values = form.exportValues(); // { 'billing.name': 'Ada Lovelace', agree: true, … }
await form.importValues(values);
```

Fields are matched by their full name. A field the form doesn't have, or a value it can't take, is
skipped; the rest still land.

To copy the fields themselves to another document, with their boxes, values and scripts, take
them out as a bundle and import it there. `FormTransfer` turns a bundle into one JSON text to
store, and back:

```ts
const bundle = await form.export(); // every field; or form.export({ fields }), ({ pages })
const text = FormTransfer.stringify(bundle);

const { fields, dropped } = await otherForm.import(await FormTransfer.parse(text));
```

The import adds the fields as one change, and one step to undo: an undo takes them away again.
When your app adds the fields by itself, pass `{ history: false }`, and undo leaves them alone. A
field whose name the form has already is left out and listed in `dropped`. By default each field
keeps who created it, which needs `canRestoreAttribution()`; pass
`{ attribution: 'stamp' }` to make them yours. See
[Import & export](https://www.embedpdf.com/docs/engine/forms/import-export.md).

**`data.ts`**

```typescript
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  signal,
  untracked,
  ViewEncapsulation,
} from '@angular/core';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfForm, EpdfFormLayer, FormTransfer, withForm } from '@embedpdf/angular/form';
import type { FormBundle } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';

const forms = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/forms.pdf');
  return { kind: 'bytes', id: 'forms', bytes: new Uint8Array(await response.arrayBuffer()) };
};

@Component({
  selector: 'demo-root',
  imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: forms }] },
      withStage(),
      withRender(),
      withInteraction(),
      withForm(),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './data.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="toolbar">
        <button type="button" class="button" (click)="export()">Export</button>
        <button type="button" class="button" (click)="remove()">Remove</button>
        <button type="button" class="button" [disabled]="!bundle()" (click)="import()">Import</button>
        @if (result()) {
          <output class="readout">{{ result() }}</output>
        }
      </div>
      <div class="viewer">
        <epdf-stage class="stage">
          <ng-template epdfPage>
            <epdf-render-layer />
            <epdf-form-layer />
          </ng-template>
        </epdf-stage>
        <pre class="values">{{ values() }}</pre>
      </div>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  private readonly form = inject(EpdfForm);
  private started = false;
  protected readonly bundle = signal<FormBundle | null>(null);
  protected readonly result = signal('');

  /** The values as plain data, keyed by full name: what you'd send to your backend. */
  protected readonly values = computed(() => {
    // The fields change with every value, so this reads them again each time.
    this.form.fields();
    return JSON.stringify(this.form.exportValues(), null, 2);
  });

  constructor() {
    // On load: the form filled in.
    effect(() => {
      if (this.form.status() !== 'ready' || this.started) return;
      this.started = true;
      untracked(() => {
        void this.form.importValues({
          name: 'Ada Lovelace',
          email: 'ada@example.com',
          framework: 'Svelte',
        });
      });
    });
  }

  protected async export() {
    const exported = await this.form.export();
    // One JSON text: what you'd store, and read back with FormTransfer.parse().
    const text = FormTransfer.stringify(exported);
    this.bundle.set(exported);
    this.result.set(`Exported ${exported.fields.length} fields, ${text.length} characters of JSON`);
  }

  protected async remove() {
    for (const field of this.form.list()) await this.form.delete(field.ref);
    this.result.set('The form is gone');
  }

  protected async import() {
    const bundle = this.bundle();
    if (!bundle) return;
    const { fields, dropped } = await this.form.import(bundle);
    this.result.set(`Imported ${fields.length} fields, left out ${dropped.length}`);
  }
}
```

**`data.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --text: #3b4b7a;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The controls, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 13px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

.readout {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
}

/* The pages and the values: stacked, and side by side where there's room */
.viewer {
  container-type: inline-size;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.stage,
.values {
  flex: 1 1 100%;
  box-sizing: border-box;
  border: 1px solid var(--line);
  border-radius: 14px;
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.stage {
  height: 340px;
  background: var(--canvas);
}

.values {
  margin: 0;
  padding: 12px 14px;
  overflow: auto;
  font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
  font-size: 12px;
  line-height: 1.5;
  color: var(--text);
  background: var(--surface);
}

@container (min-width: 620px) {
  .stage {
    flex: 1 1 0;
    min-width: 0;
    height: 440px;
  }

  .values {
    flex: 0 0 230px;
    max-height: 440px;
  }
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

## Methods

What `inject(EpdfForm)` gives you for reading and filling. The verbs that change the form itself are
on [Building forms](https://www.embedpdf.com/docs/headless/angular/forms/building.md#methods).

| Method                                                        | What it does                                                                                                                                                                                                                                                                                                          |
| :------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get(ref)`                                                    | One field, with its value, or `null` when the form has no such field. [Read the form](#read-the-form)                                                                                                                                                                                                                 |
| `getValue(ref)`                                               | One field's value, in the shape `setValue()` takes, or `null`. In a component, use `form.valueOf(ref)`.                                                                                                                                                                                                               |
| `getFieldForWidget(widget)`                                   | The field a box belongs to, from the box's ref                                                                                                                                                                                                                                                                        |
| `getWidget(widget)`                                           | A box's row: its page, its place (`rect`), its look and its state, or `null` when no page shows it                                                                                                                                                                                                                    |
| `getWidgets(ref)`                                             | Every box a field shows in, as rows in the field's order: a radio group's buttons, or a field repeated on several pages                                                                                                                                                                                               |
| `listGroups()`                                                | Every group `setGroups()` named, then every other group the form's fields are in, as `{ id, label, color }`. [Fields for several people](#fields-for-several-people)                                                                                                                                                  |
| `setGroups(groups)`                                           | Says who this document's groups are, `{ id, label, color }` each: the whole list, and `[]` clears it. Fires `groupsChanged$`. [Fields for several people](#fields-for-several-people)                                                                                                                                 |
| `listWidgets(page)`                                           | Each field box on a page, with its place (`box`, `rotation` and `rect`), its control, its value and whether it can be filled. For drawing the fields yourself; see [What a box tells you](https://www.embedpdf.com/docs/headless/angular/forms/controls.md#what-a-box-tells-you) and [Turned fields](#turned-fields). |
| `getWidgetAt(page, point)`                                    | The field box under a point on a page, with its field and its place (`box`, `rotation` and `rect`), or `null`                                                                                                                                                                                                         |
| `setValue(ref, value)`                                        | Fills in a field with `{ value }`, `{ checked }` or `{ selectedValues }`, running the form's checks and scripts. Resolves `{ field, status }`. [Fill in a field](#fill-in-a-field)                                                                                                                                    |
| `setValues(entries)`                                          | Fills in several fields, each `{ ref, value }`, as one change with one recalculation; a field you may not fill in, or a value it can't take, fails on its own. Resolves `{ applied, skipped, failed }`.                                                                                                               |
| `setButtonImage(ref, image)`                                  | Puts a picture into an image field, `{ source }`, or takes it out, `null`, as one step to undo. Resolves `{ field }`. [Image fields](#image-fields)                                                                                                                                                                   |
| `importValues(values)`                                        | Fills in fields by full name from a plain object, as one change with one recalculation. Resolves `{ applied, skipped, failed }`. [Move form data in and out](#move-form-data-in-and-out)                                                                                                                              |
| `prefill()`                                                   | Fills in the user's empty fields whose purpose the app has a value for, as one change. Resolves `{ applied, skipped, failed }`. [Values the app already knows](#values-the-app-already-knows)                                                                                                                         |
| `exportValues()`                                              | Every value, keyed by full name, as a plain object                                                                                                                                                                                                                                                                    |
| `export(selection?)`                                          | Whole fields with their boxes, values and scripts, as a bundle: every field, or `{ fields }` or `{ pages }`. [Move form data in and out](#move-form-data-in-and-out)                                                                                                                                                  |
| `import(bundle, options?)`                                    | Adds a bundle's fields, as one change and one step to undo. Resolves `{ fields, refMap, dropped }`. Needs `canDesign()`. [Move form data in and out](#move-form-data-in-and-out)                                                                                                                                      |
| `reset(refs?)`                                                | Puts back each field's default, for every field the user may fill in or the fields you pass. Resolves `{ fields }`, the fields it changed. [Reset the form](#reset-the-form)                                                                                                                                          |
| `validate()`                                                  | Checks the required fields the user fills in. Returns `{ valid, missing, required }`: the empty ones, and all of them, in page order. [Check required fields](#check-required-fields)                                                                                                                                 |
| `validateValues()`                                            | Checks the required fields, and every value against the form's own rules, without writing. Resolves `{ valid, missing, required, invalid }`. [Check the values too](#check-the-values-too)                                                                                                                            |
| `listPurposes()`                                              | Every purpose the viewer knows, each as `{ id, label }`, the label in the viewer's language. [What a field is for](https://www.embedpdf.com/docs/headless/angular/forms/building.md#what-a-field-is-for)                                                                                                              |
| `focus(ref, options?)`                                        | Brings a field into view and puts the cursor in it; `{ select: true }` selects its text. Returns `false` for a field the user can't fill in. [Move between fields](#move-between-fields)                                                                                                                              |
| `focusNext(options?)`                                         | Moves the cursor to the next field, as Tab does: `{ backward, empty, required, wrap }`. Returns `false` when there's none. [Move between fields](#move-between-fields)                                                                                                                                                |
| `getFocusedField()`                                           | The field the cursor is in, or `null`                                                                                                                                                                                                                                                                                 |
| `activateWidget(widget)`                                      | Does what a click on a field box does, such as running a button's action                                                                                                                                                                                                                                              |
| `getSnapshot()`                                               | Everything at once, as the user sees it: what the engine's `list()` returns, with the values still on their way. `fields`, `widgets`, `formKind`, `needsAppearances` and `calculationOrder`                                                                                                                           |
| `refresh()`                                                   | Reads the whole form again, and `resynced$` fires. You rarely need it: the plugin follows every change, whoever made it.                                                                                                                                                                                              |
| `canRead()`, `canFill(ref)`                                   | Whether reading the form, and filling in a field, are allowed. [Permissions](#permissions)                                                                                                                                                                                                                            |
| `getSettings()`, `updateSettings(changes)`, `resetSettings()` | Reads the settings, changes them while the app runs, or goes back to what you registered. In a component, use `inject(EpdfForm).settings()`. [Settings](#settings)                                                                                                                                                    |

Every method that returns a promise also takes a `signal` in its options, to cancel it.

## State

Every value is a signal on `inject(EpdfForm)`: read it in a template or a `computed()`, and your view updates when it changes. The method in the last column reads the same value once.

| Field                | What it is                                                                                                                                                                                                                          | Read once                                          |
| :------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- |
| `fields()`           | Every field, with its value                                                                                                                                                                                                         | `list()`, or `list({ kind, page, name })` for some |
| `status()`           | Whether the form is read: `'idle'`, `'loading'`, `'ready'`, `'forbidden'` or `'error'`                                                                                                                                              | `getStatus()`                                      |
| `formKind()`         | What the document has: `'none'`, `'acroform'` (a regular PDF form) or `'xfa'`                                                                                                                                                       | `getFormKind()`                                    |
| `selectedField()`    | In design mode, the field whose boxes are selected (one, or several of the same field), or `null`; see [Building forms](https://www.embedpdf.com/docs/headless/angular/forms/building.md#change-a-fields-settings)                  | `getSelectedField()`                               |
| `focusedField()`     | The field the cursor is in, or `null`; see [Move between fields](#move-between-fields)                                                                                                                                              | `getFocusedField()`                                |
| `selectedFields()`   | In design mode, every field with a selected box; see [Building forms](https://www.embedpdf.com/docs/headless/angular/forms/building.md#give-fields-to-a-signer)                                                                     | `listSelectedFields()`                             |
| `groups()`           | Every group you named or the form's fields are in, as `{ id, label, color }`; see [Fields for several people](#fields-for-several-people)                                                                                           | `listGroups()`                                     |
| `designGroup()`      | In design mode, the group that fields placed with a tool go in, or `null` for none, and while they are for anyone; see [Building forms](https://www.embedpdf.com/docs/headless/angular/forms/building.md#place-fields-for-a-signer) | `getDesignGroup()`                                 |
| `designAssignment()` | In design mode, who fields placed with a tool are for: a group, anyone or nobody; see [Building forms](https://www.embedpdf.com/docs/headless/angular/forms/building.md#place-fields-anyone-fills-in)                               | `getDesignAssignment()`                            |
| `designing()`        | Whether the form is being designed now: a design tool is active for a user who may design; see [Building forms](https://www.embedpdf.com/docs/headless/angular/forms/building.md#design-mode)                                       | `isDesigning()`                                    |

For one field, `form.valueOf(ref)` updates only when that field's value changes.

## Settings

Set them when you register the plugin, and change them while the app runs with
`form.updateSettings({ … })`; `form.resetSettings()` goes back to what you registered, and
`inject(EpdfForm).settings()` gives you the current settings.

| Setting                  | What it does                                                                                                                                                                                                                                                                   | Default                     | From CSS                              |
| :----------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------- | :------------------------------------ |
| `validation`             | Run the form's own checks (`'scripts'`), or accept every value (`'none'`)                                                                                                                                                                                                      | `'scripts'`                 | —                                     |
| `focus.color`            | The ring around the field the cursor is in                                                                                                                                                                                                                                     | the viewer's accent         | `--epdf-form-focus`                   |
| `fields.border`          | The edge of a field that has no border of its own and no tint: on the fields the user fills in, and on every field in design mode. See [A field's look and its tint](#a-fields-look-and-its-tint)                                                                              | the viewer's accent at 55%  | `--epdf-form-field-border`            |
| `fields.background`      | Inside a field that has no background of its own                                                                                                                                                                                                                               | `'rgb(255 255 255 / 0.92)'` | `--epdf-form-field-background`        |
| `fields.color`           | The check mark and text of a field that has no color of its own                                                                                                                                                                                                                | `'#1f2a44'`                 | `--epdf-form-field-color`             |
| `fillable`               | Which fields people fill in by hand: `true`, `false`, or field kinds                                                                                                                                                                                                           | `true`                      | —                                     |
| `fields.tint`            | How strongly a field shows its [tint](#a-fields-look-and-its-tint), from `0`, not at all, to `1`                                                                                                                                                                               | `0.16`                      | `--epdf-form-field-tint`              |
| `fields.tintColor`       | The tint of a field in no group, a CSS color. `null` leaves such a field untinted. See [A field's look and its tint](#a-fields-look-and-its-tint)                                                                                                                              | `null`                      | `--epdf-form-field-tint-color`        |
| `fields.anyoneTintColor` | The tint of a field anyone fills in, a CSS color. `null` gives it `fields.tintColor`. See [Fields anyone fills in](#fields-anyone-fills-in)                                                                                                                                    | `'#0891b2'`                 | `--epdf-form-field-anyone-tint-color` |
| `fields.placeholder`     | What an empty field shows, its own [placeholder](https://www.embedpdf.com/docs/headless/angular/forms/building.md#a-fields-placeholder) or its [purpose's](https://www.embedpdf.com/docs/headless/angular/forms/building.md#what-a-field-is-for) label: the color of that text | `'rgb(31 42 68 / 0.55)'`    | `--epdf-form-field-placeholder`       |
| `fields.required`        | The edge of a required field of the user's that is still empty, a CSS color. `null` shows none. See [Check required fields](#check-required-fields)                                                                                                                            | `null`                      | `--epdf-form-field-required`          |
| `tools`                  | Your own field tools. [Make your own field tool](https://www.embedpdf.com/docs/headless/angular/forms/building.md#make-your-own-field-tool)                                                                                                                                    | `[]`                        | —                                     |

Scripts need JavaScript on in the actions plugin. Without it, `'scripts'` still checks a
[date or a time](#dates) against its field's pattern and accepts every other value, and a form
with scripts logs a hint once. `'none'` checks nothing, dates included.

`fillable` is for the people using your app. A field it leaves out draws as a read-only field
does, and takes no typing, clicks or picks; your code still fills it in with `setValue()` and
`importValues()`, and `canFill(ref)` doesn't change:

```ts
withForm({ fillable: false }); // show the values, take no input
form.updateSettings({ fillable: ['text', 'checkbox'] }); // only these kinds
form.updateSettings({ fillable: true }); // every field again
```

The kinds are `'text'`, `'checkbox'`, `'radio'`, `'combobox'`, `'listbox'`, `'pushbutton'` and
`'signature'` (signing a field is filling it in). To stop your code too, leave `doc.forms.fill` out
of the scope (see [Permissions](#permissions)).

The colors are what the viewer draws around fields; a field's own colors are saved in the PDF (see
[Building forms](https://www.embedpdf.com/docs/headless/angular/forms/building.md)). A required field has no edge of its own until you give
`fields.required` a color. A CSS variable wins over the setting: see
[Colors & theming](https://www.embedpdf.com/docs/headless/angular/ui/theming.md).

`tools` is read when a document opens, so set it when you register the plugin.

**`colors.ts`**

```typescript
import { ChangeDetectionStrategy, Component, inject, ViewEncapsulation } from '@angular/core';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfForm, EpdfFormLayer, withForm } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';

const forms = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/forms.pdf');
  return { kind: 'bytes', id: 'forms', bytes: new Uint8Array(await response.arrayBuffer()) };
};

const COLORS = [
  ['Accent', null],
  ['Orange', '#ea580c'],
  ['Green', '#16a34a'],
] as const;

@Component({
  selector: 'demo-root',
  imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: forms }] },
      withStage(),
      withRender(),
      withInteraction(),
      // The colors the viewer draws around fields; `null` follows the viewer's accent.
      withForm({ fields: { border: '#ea580c' } }),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './colors.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="toolbar">
        <span class="label">Edges</span>
        <div class="segments">
          @for (color of colors; track color[0]) {
            <button
              type="button"
              class="segment"
              [attr.aria-pressed]="form.settings().fields.border === color[1]"
              (click)="form.updateSettings({ fields: { border: color[1] } })"
            >
              {{ color[0] }}
            </button>
          }
        </div>
        <span class="label">Focus</span>
        <div class="segments">
          @for (color of colors; track color[0]) {
            <button
              type="button"
              class="segment"
              [attr.aria-pressed]="form.settings().focus.color === color[1]"
              (click)="form.updateSettings({ focus: { color: color[1] } })"
            >
              {{ color[0] }}
            </button>
          }
        </div>
      </div>
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-form-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  protected readonly form = inject(EpdfForm);
  protected readonly colors = COLORS;
}
```

**`colors.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --accent: #054fb3;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The color choices, above the pages */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px 10px;
  margin-bottom: 14px;
}

.label {
  font-size: 12px;
  font-weight: 600;
  color: var(--muted);
}

.segments {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 2px;
  padding: 3px;
  background: var(--tint);
  border: 1px solid var(--line);
  border-radius: 10px;
}

.segment {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--muted);
  background: transparent;
  border: 0;
  border-radius: 7px;
  padding: 7px 12px;
  cursor: pointer;
}

.segment:hover {
  color: var(--ink);
}

.segment[aria-pressed='true'] {
  color: var(--accent);
  background: var(--surface);
  box-shadow: 0 1px 3px rgb(7 32 76 / 0.12);
}

.segment:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 1px;
}

/* The pages */
.stage {
  height: 440px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

## Events

**`autosave.ts`**

```typescript
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { EpdfForm } from '@embedpdf/angular/form';
import { autosave } from './api';

@Component({ selector: 'app-autosave', template: '' })
export class Autosave {
  constructor() {
    inject(EpdfForm)
      .valueChanged$.pipe(takeUntilDestroyed())
      .subscribe(({ field }) => autosave(field.name));
  }
}
```

| Event                 | Fires when                                                               | Carries                   |
| :-------------------- | :----------------------------------------------------------------------- | :------------------------ |
| `valueChanged$`       | A field's value changed                                                  | `field`, `origin`         |
| `validationRejected$` | The form's validation refused a value                                    | `field`, `issues`         |
| `focusChanged$`       | The cursor moved into a field, to another one, or out of the fields      | `field`, `widget`         |
| `resynced$`           | The whole form was read, as when it opens, after `refresh()` or a repair | `snapshot`                |
| `groupsChanged$`      | `setGroups()` changed who the document's groups are                      | `groups`                  |
| `settingsChanged$`    | The settings changed                                                     | `settings`, `changedKeys` |

Fields that are added, changed or removed have their own events; see
[Building forms](https://www.embedpdf.com/docs/headless/angular/forms/building.md#events).

## Permissions

| Permission       | What it allows   | Check               |
| :--------------- | :--------------- | :------------------ |
| `doc.forms.read` | Reading the form | `form.canRead()`    |
| `doc.forms.fill` | Filling it in    | `form.canFill(ref)` |

Without it, the fields show their values but can't be changed. A user with a `fields:fill`
permission for one group fills in that group's fields only: `form.canFill(ref)` answers per field,
the other fields can't be changed and Tab skips them, `validate()` leaves them out, and `reset()`
leaves them as they are. A field [anyone fills in](#fields-anyone-fills-in) is theirs too. See
[Signers and groups](https://www.embedpdf.com/docs/engine/forms/groups.md).

A field a signature [locked](#signed-documents) is nobody's to fill in, whatever their
permissions: `form.canFill(ref)` is `false` for it, and it is left out the same way.

## Good to know

### Forms and annotations

A field's widgets are the form's: the annotation plugin never lists them. With the
[annotation plugin](https://www.embedpdf.com/docs/headless/angular/annotations.md) registered, the `<epdf-form-layer>` and the annotation layer share the page: fields stay fillable with the
`pointer` tool, and become movable boxes in [design mode](https://www.embedpdf.com/docs/headless/angular/forms/building.md#design-mode). Under any
other tool, such as a stamp or a pen, they show as they do while filling but take no input, so the
tool works over them.

### Keyboard

Tab and Shift+Tab move between fields in the document's order (see [Move between
fields](#move-between-fields)), and the arrow keys between the buttons of a radio group. In a text
box, Enter confirms and Escape puts back the value it had.

### Screen readers

Each control is named by the field's tooltip (its `alternateName`), or by its name when it has
none. A radio button adds the option it stands for, its export value, the way screen readers read
one in Acrobat: `Plan: monthly`. It also says where it comes in its group (`1 of 2`, in the order
the arrow keys go round), since a group's buttons stand apart on the page. A field of a
[group you named](#fields-for-several-people) says whose it is last: `Plan: monthly, Dana Smith`,
and a field [anyone fills in](#fields-anyone-fills-in) says `Anyone`.

A required field says so where its control can: the control of a text box, a checkbox, a
dropdown and a list has `aria-required`, whether or not `fields.required` draws an edge. Three
controls don't say it:

- **A radio button.** The state belongs to a radio group, not to a button in it, and a group's
  buttons stand apart on the page with no element around them. So the layer's radio buttons
  don't expose that their group is required.
- **A signature field and an image field.** Their control is a button, and a button has no such
  state.

All of them still count in [`validate()`](#check-required-fields) and show the `fields.required`
edge.

When you draw the fields
yourself, each entry of `listWidgets(page)` carries the name as `label`, whether the form asks
for a value as `required`, and a radio button its place as `inGroup`, `{ position, size }`, for
`aria-posinset` and `aria-setsize`. Where you put a group's buttons in an element of your own
with the role `radiogroup`, that element is the place for `aria-required`.

### Turned fields

A field can be turned a quarter turn: so that it reads upright on a page that is shown turned, such
as a scan saved sideways, or so that a label runs up the side of a page. `<epdf-form-layer>` places each
control in the field's frame and turns it with the field, so people type, tick and pick in the
direction the field reads. A dropdown's open list is the browser's own, and opens unturned.

When you draw the fields yourself, each entry of `listWidgets(page)` says where it is with three
values:

| Value      | What it is                                                               |
| :--------- | :----------------------------------------------------------------------- |
| `box`      | The frame the field's contents are laid out in, before the turn          |
| `rotation` | The turn, clockwise about the middle of `box`: `0`, `90`, `180` or `270` |
| `rect`     | Where the field stands on the page: `box` turned                         |

Place your control at `box` and turn it by `rotation` about its middle: it then covers `rect`. For
a field that isn't turned, `box` and `rect` are the same and `rotation` is `0`.

### Collecting responses

On the local engine, the values live in the document in this tab until it's downloaded.

> **Collect form responses on your server**
>
> With CloudPDF, each value is stored on your server as it's entered, so a half-filled form survives a
> closed tab, and your backend reads the answers without asking the user to download or upload a
> file.
>
> [Collect forms with CloudPDF](https://www.cloudpdf.com/docs/headless/angular/forms.md)

### XFA forms

Some PDFs also carry a form in the older XFA format. The viewer works with the document's regular
fields and never runs XFA; see [Forms](https://www.embedpdf.com/docs/engine/forms.md#xfa-forms).

### Signed documents

A signature can lock the whole form, or some fields. Locked fields show their values and can't be
changed: `form.canFill(ref)` is `false` for one, its box is `disabled`, and its field says which
signature locked it, as `lockedBy`. That holds right after a signing in your app too, and for a
lock another PDF app wrote without marking the field read-only. See [Signatures](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md).
