---
title: "A signing flow — Angular"
description: "Send one document to several signers. Place each signer's fields in their own color, let each fill in and sign only theirs, guide them to what's left, and seal each part with one signature."
framework: "Angular"
other_frameworks:
  "React": "https://www.embedpdf.com/docs/headless/react/forms/signing-flow.md"
  "Vue": "https://www.embedpdf.com/docs/headless/vue/forms/signing-flow.md"
  "Svelte": "https://www.embedpdf.com/docs/headless/svelte/forms/signing-flow.md"
source: "https://www.embedpdf.com/docs/headless/angular/forms/signing-flow"
---

# A signing flow

A contract goes to two people. Dana fills in her part and signs it, then Lanternfield's director
does the same. Each works in their own browser, sees which fields are theirs, and can change nothing
else. This page builds that from start to finish, with parts the other form pages describe one by
one.

Three kinds of people use your app:

| Who           | Does                                        | Uses                                                                                                                 |
| :------------ | :------------------------------------------ | :------------------------------------------------------------------------------------------------------------------- |
| The sender    | Places each signer's fields on the document | [Design mode](https://www.embedpdf.com/docs/headless/angular/forms/building.md#design-mode), with the signers listed |
| Each signer   | Fills in their own fields and signs         | The form layer, with permissions for their own fields                                                                |
| Anyone, later | Checks who signed, and that nothing changed | [Check the signatures](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#check-the-signatures)      |

**`signing-flow.ts`**

```typescript
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  type ElementRef,
  inject,
  input,
  output,
  signal,
  untracked,
  viewChild,
  ViewEncapsulation,
} from '@angular/core';
import {
  EpdfDocument,
  EpdfDocumentGate,
  EpdfDocuments,
  EpdfViewer,
  provideEmbedPdf,
} from '@embedpdf/angular/runtime';
import type { OpenInput, PageRef } 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 { EpdfAnchored } from '@embedpdf/angular/anchored';
import { EpdfForm, EpdfFormLayer, withForm } from '@embedpdf/angular/form';
import type { FormField, FormFieldDraft } from '@embedpdf/angular/form';
import { createTestSigner, EpdfSignature, withSignature } from '@embedpdf/angular/signature';
import { localEngine } from '@embedpdf/engine';

const engine = localEngine();

// A throwaway key for each signer. In your app a signer's page has one key, as the
// `signingKey` setting: `webCryptoSigner`, `remoteSigner` or `personalSigner`.
const keys = {
  borrower: createTestSigner({ commonName: 'Dana Smith' }),
  approver: createTestSigner({ commonName: 'Ada Lovelace' }),
};

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', color: '#0f766e' },
];

// What each person may do, as permissions, and who each signer is. A signer fills in and signs
// the fields of their own group, and nothing else.
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:all'],
    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' },
  },
  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' },
  },
};
type Person = keyof typeof people;
type Signer = Exclude<Person, 'sender'>;

// The fields the sender placed on the printed form, each in its signer's group. A field has no
// border of its own here: the printed box is its look.
const bare = { color: null, interiorColor: null };
const fieldsOn = (page: PageRef): FormFieldDraft[] => {
  const box = (x: number, y: number, width = 229, height = 22) => ({
    widgets: [{ page, rect: { x, y, width, height }, ...bare, fontSize: 11 }],
  });
  const tick = (name: string, alternateName: string, x: number): FormFieldDraft => ({
    kind: 'checkbox',
    name,
    alternateName,
    groupId: 'borrower',
    widgets: [{ page, rect: { x, y: 254.96, width: 16, height: 16 }, ...bare }],
  });
  const partOf = (groupId: Signer, x: number): FormFieldDraft[] => [
    {
      kind: 'text',
      name: `${groupId}.name`,
      alternateName: 'Name',
      groupId,
      purpose: 'name',
      required: true,
      ...box(x, 341.8),
    },
    {
      kind: 'text',
      name: `${groupId}.date`,
      alternateName: 'Date',
      groupId,
      purpose: 'date-signed',
      format: { kind: 'date', pattern: 'yyyy-mm-dd' },
      readOnly: true,
      ...box(x, 390.55),
    },
    {
      kind: 'signature',
      name: `${groupId}.signature`,
      alternateName: 'Signature',
      groupId,
      purpose: 'signature',
      required: true,
      ...box(x, 439.3, 229, 61),
    },
  ];
  return [
    {
      kind: 'text',
      name: 'loan.item',
      alternateName: 'Item',
      groupId: 'borrower',
      required: true,
      ...box(61, 201.71),
    },
    {
      kind: 'text',
      name: 'loan.serial',
      alternateName: 'Serial number',
      groupId: 'borrower',
      ...box(322, 201.71),
    },
    {
      kind: 'text',
      name: 'loan.return',
      alternateName: 'Return by',
      groupId: 'borrower',
      required: true,
      ...box(61, 251.96),
    },
    tick('loan.charger', 'Charger', 322),
    tick('loan.case', 'Carrying case', 404.89),
    ...partOf('borrower', 61),
    ...partOf('approver', 322),
  ];
};

/**
 * The sender's part, done in code so the example starts with the signers: the fields go onto
 * the printed form, each in its signer's group. Building forms shows a sender doing it by hand.
 */
@Component({
  selector: 'demo-prepare',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="toolbar">
      <output class="readout">The sender is placing the fields…</output>
    </div>
  `,
})
export class Prepare {
  readonly done = output();

  private readonly form = inject(EpdfForm);
  private readonly document = inject(EpdfDocument);
  private started = false;

  constructor() {
    effect(() => {
      const page = this.document.pages()[0]?.ref; // the printed form
      if (!page || this.started) return;
      this.started = true;
      untracked(() => void this.place(page));
    });
  }

  private async place(page: PageRef) {
    for (const draft of fieldsOn(page)) await this.form.create(draft);
    this.done.emit();
  }
}

/** What a person reads a field as: its tooltip. */
const nameOf = (field: FormField) => field.alternateName ?? field.name;

/**
 * The guide: how much is left, the way to the next field, and Finish. It is drawn from what
 * the plugins say: `validate()`, `focusNext()`, `canFinish()` and `finish()`.
 */
@Component({
  selector: 'demo-guide',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="toolbar">
      <!-- Nothing left for this person to sign: they finished, and their fields are final. -->
      @if (!signature.canFinish()) {
        <output class="readout">{{ signed() }}</output>
        @if (handsOver()) {
          <button type="button" class="button" (click)="handOver.emit()">
            Hand over to Ada Lovelace
          </button>
        }
      } @else {
        <span class="legend">
          <i class="swatch" [style.background]="color()"></i>{{ people[person()].name }}
        </span>
        <output class="readout">{{ progress() }}</output>
        <button
          type="button"
          class="button"
          [disabled]="check().missing.length === 0"
          (click)="form.focusNext({ required: true, empty: true, wrap: true })"
        >
          Next
        </button>
        <span class="divider"></span>
        <label class="consent">
          <input
            #consent
            type="checkbox"
            [checked]="agreed()"
            (change)="agreed.set(consent.checked)"
          />
          I agree to sign electronically
        </label>
        <button
          type="button"
          class="button"
          [disabled]="!agreed() || signature.busy()"
          (click)="finish()"
        >
          Finish
        </button>
        @if (problems().length > 0) {
          <output class="problems">Still to do: {{ problems().join(', ') }}</output>
        }
      }
    </div>
  `,
})
export class Guide {
  readonly person = input.required<Signer>();
  /** Whether the form goes to another signer once this one finished. */
  readonly handsOver = input(false);
  readonly handOver = output();

  protected readonly form = inject(EpdfForm);
  protected readonly signature = inject(EpdfSignature);
  protected readonly people = people;
  protected readonly agreed = signal(false);
  protected readonly problems = signal<string[]>([]);

  protected readonly color = computed(
    () => signers.find((each) => each.id === this.person())?.color,
  );

  /** 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();
  });

  protected readonly progress = computed(() => {
    const { required, missing } = this.check();
    return `${required.length - missing.length} of ${required.length} filled in`;
  });

  /** Who signed, and what the check of each signature says. */
  protected readonly signed = computed(() =>
    this.signature
      .signatures()
      .map((each) => `${each.signer?.name}: ${each.verdict?.summary ?? 'checking…'}`)
      .join(' · '),
  );

  constructor() {
    // The signer starts: the app fills in what it knows, their name and today's date.
    void this.form.prefill();

    // What Finish said is left stands until the form changes.
    effect(() => {
      this.form.fields();
      this.problems.set([]);
    });
  }

  // Consent is your app's: ask before you call `finish()`. It checks the signer's fields,
  // writes the day of signing, and signs with the mark that is in the signature field.
  protected async finish() {
    const person = this.person();
    const result = await this.signature.finish({
      signingKey: () => keys[person],
      signer: { reason: 'I agree to the terms of this loan' },
    });
    if (result.status === 'signed') return this.problems.set([]);
    this.problems.set([
      ...result.missing.map(nameOf),
      ...result.invalid.map(({ field, message }) => `${nameOf(field)}: ${message ?? 'not valid'}`),
    ]);
    this.form.focus((result.missing[0] ?? result.invalid[0]!.field).ref);
  }
}

const INK = '#1d2b53';
type Point = { x: number; y: number };

/**
 * A signer pressed their signature field, with a click or with Tab and Space: the field is the
 * signature plugin's target, and this card opens next to it. What they draw goes into the field,
 * in place of a mark it holds, and nothing is sealed until they finish.
 */
@Component({
  selector: 'demo-sign-card',
  imports: [EpdfAnchored],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    @if (signature.target()) {
      <epdf-anchored [anchor]="anchor()" placement="bottom-start" [gap]="8">
        <div
          #card
          class="sign-card"
          role="dialog"
          aria-label="Draw your signature"
          tabindex="-1"
          (keydown.escape)="close()"
        >
          <canvas
            #pad
            class="sign-pad"
            width="240"
            height="100"
            (pointerdown)="start($event)"
            (pointermove)="draw($event)"
          ></canvas>
          <div class="sign-actions">
            @if (hasMark()) {
              <button type="button" class="button" (click)="remove()">Remove</button>
            }
            <button type="button" class="button" (click)="close()">Cancel</button>
            <button type="button" class="button" [disabled]="!drawn()" (click)="place()">
              {{ hasMark() ? 'Replace' : 'Place' }}
            </button>
          </div>
        </div>
      </epdf-anchored>
    }
  `,
})
export class SignCard {
  private readonly form = inject(EpdfForm);
  protected readonly signature = inject(EpdfSignature);
  private readonly row = computed(() => {
    const target = this.signature.target();
    return target ? this.form.getWidgets(target)[0] : undefined;
  });
  protected readonly anchor = this.form.widgetAnchorOf(() => this.row()?.ref ?? null);
  protected readonly hasMark = computed(() => this.row()?.hasMark ?? false);
  protected readonly drawn = signal(false);

  private readonly card = viewChild<ElementRef<HTMLDivElement>>('card');
  private readonly pad = viewChild<ElementRef<HTMLCanvasElement>>('pad');
  private last: Point | null = null;

  constructor() {
    // Each field starts with an empty pad, and the card takes the cursor, so Escape closes it.
    effect(() => {
      const target = this.signature.target();
      const pad = this.pad()?.nativeElement;
      this.last = null;
      this.drawn.set(false);
      pad?.getContext('2d')?.clearRect(0, 0, pad.width, pad.height);
      if (target) this.card()?.nativeElement.focus();
    });
  }

  private pointOf(event: PointerEvent, canvas: HTMLCanvasElement): Point {
    const box = canvas.getBoundingClientRect();
    return { x: event.clientX - box.left, y: event.clientY - box.top };
  }

  protected start(event: PointerEvent) {
    const canvas = event.currentTarget as HTMLCanvasElement;
    canvas.setPointerCapture(event.pointerId);
    this.last = this.pointOf(event, canvas);
  }

  protected draw(event: PointerEvent) {
    const canvas = event.currentTarget as HTMLCanvasElement;
    const from = this.last;
    const ink = canvas.getContext('2d');
    if (!from || !ink || !canvas.hasPointerCapture(event.pointerId)) return;
    const to = this.pointOf(event, canvas);
    this.last = to;
    ink.strokeStyle = INK;
    ink.lineWidth = 2;
    ink.lineCap = 'round';
    ink.beginPath();
    ink.moveTo(from.x, from.y);
    ink.lineTo(to.x, to.y);
    ink.stroke();
    this.drawn.set(true);
  }

  // Close without a change, and put the cursor back on the field.
  protected close(field = this.signature.target()) {
    this.signature.setTarget(null);
    if (field) this.form.focus(field);
  }

  // The drawing goes into the field as a picture, in place of the one it holds.
  protected place() {
    const field = this.signature.target();
    this.pad()?.nativeElement.toBlob(async (png) => {
      if (!field || !png) return;
      await this.signature.placeMark({ source: png }, { field });
      this.form.focus(field);
    });
  }

  // Take the mark out again: the field is empty, and still theirs to sign.
  protected async remove() {
    const field = this.signature.target();
    if (!field) return;
    await this.signature.clearField(field);
    this.close(field);
  }
}

/** Names the open document's groups, and shows the sender's part or a signer's guide. */
@Component({
  selector: 'demo-toolbar',
  imports: [Prepare, Guide],
  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-prepare (done)="next.emit()" />
    } @else if (signer(); as signer) {
      <demo-guide [person]="signer" [handsOver]="signer === 'borrower'" (handOver)="next.emit()" />
    }
  `,
})
export class Toolbar {
  readonly person = input.required<Person>();
  readonly next = output();

  protected readonly form = inject(EpdfForm);
  protected readonly signer = computed(() => {
    const person = this.person();
    return person === 'sender' ? null : person;
  });

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

@Component({
  selector: 'demo-root',
  imports: [
    EpdfDocumentGate,
    EpdfStage,
    EpdfPageTemplate,
    EpdfRenderLayer,
    EpdfFormLayer,
    Toolbar,
    SignCard,
  ],
  providers: [
    provideEmbedPdf(
      {
        engine,
        scope: people.sender.scope,
        identity: people.sender.identity,
        initialDocuments: [{ source: loan, name: 'equipment-loan.pdf' }],
      },
      withStage(),
      withRender(),
      withInteraction(),
      withForm(),
      withSignature({
        // A mark placed in a signature field is only drawn in: `finish()` seals, as the last step.
        mode: 'finish',
        // Trust the demo keys themselves, so their signatures check out as 'valid'.
        trust: {
          anchors: async () =>
            (await Promise.all([keys.borrower, keys.approver])).map((key) => key.certificate),
        },
      }),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './signing-flow.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: opening">
      <demo-toolbar [person]="person()" (next)="handOver()" />
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-form-layer />
        </ng-template>
        <demo-sign-card />
      </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 person = signal<Person>('sender');

  // A document keeps who it opened for, so the next person opens the saved form again.
  protected async handOver() {
    const person = this.person() === 'sender' ? 'borrower' : 'approver';
    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' });
  }
}
```

**`signing-flow.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);
}

/* One of several */
.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;
}

/* Who a field is for: a signer's color, beside their name */
.label {
  font-size: 13px;
  font-weight: 600;
  color: var(--muted);
}

.swatch {
  display: inline-block;
  width: 10px;
  height: 10px;
  margin-right: 6px;
  border-radius: 3px;
}

.legend {
  display: inline-flex;
  align-items: center;
  font-size: 13px;
  font-weight: 550;
  color: var(--ink);
}

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

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

/* The card a signer draws their signature in */
.sign-card {
  display: grid;
  gap: 8px;
  padding: 10px;
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 12px;
  box-shadow: 0 12px 32px -12px rgb(7 32 76 / 0.35);
}

.sign-card:focus {
  outline: none;
}

.sign-pad {
  display: block;
  width: 240px;
  height: 100px;
  background: var(--canvas);
  border: 1px dashed var(--line-strong);
  border-radius: 8px;
  cursor: crosshair;
  touch-action: none;
}

.sign-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* The guide: agreeing, and what is still to do */
.consent {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  font-weight: 550;
  color: var(--ink);
  cursor: pointer;
}

.consent input {
  width: 15px;
  height: 15px;
  margin: 0;
  accent-color: var(--accent);
}

.problems {
  flex-basis: 100%;
  font-size: 13px;
  font-weight: 600;
  color: #b45309;
}

/* 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 sender's fields are placed for you. As **Dana Smith**, press **Next** and type
> an item and a return date. Click her Signature box, draw, and press **Place**; click the box
> again to replace the drawing or take it out. Tick the box to agree and press **Finish**: her
> part is signed, and her fields take no more input. **Hand over to Ada Lovelace**: she sees
> Dana's part as Dana left it, signs her own, and both signatures check out.

## Name the signers

Every field belongs to a **group**, and each signer gets the permissions for one group; see
[Signers and groups](https://www.embedpdf.com/docs/engine/forms/groups.md). The PDF holds only the group's id. Who that is, and
which color shows their fields, is your app's to say, for each document it opens:

**`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()));
  }
}
```

Give the sender's page and each signer's the same list, and everyone sees the same colors.
[Fields for several people](https://www.embedpdf.com/docs/headless/angular/forms.md#fields-for-several-people) has every detail.

## The sender places the fields

In [design mode](https://www.embedpdf.com/docs/headless/angular/forms/building.md#design-mode) the sender picks who the next fields are for, then a tool,
and clicks on the page:

**`sender-toolbar.ts`**

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

@Component({
  selector: 'app-sender-toolbar',
  template: `
    @for (group of form.groups(); track group.id) {
      <button
        [attr.aria-pressed]="form.designGroup() === group.id"
        [disabled]="!form.canSetGroup(group.id)"
        (click)="form.setDesignGroup(group.id)"
      >
        <i [style.background]="group.color"></i> {{ group.label ?? group.id }}
      </button>
    }

    @for (tool of tools; track tool.id) {
      <button
        [attr.aria-pressed]="interaction.activeToolId() === tool.id"
        (click)="interaction.activateTool(tool.id)"
      >
        {{ tool.label }}
      </button>
    }
  `,
})
export class SenderToolbar {
  protected readonly form = inject(EpdfForm);
  protected readonly interaction = inject(EpdfInteraction);

  protected readonly tools = [
    { id: 'form-text', label: 'Text' },
    { id: 'form-checkbox', label: 'Checkbox' },
    { id: 'signer-signature', label: 'Signature' },
  ];
}
```

`setDesignGroup()` says who the next fields are for. The signing tools place fields that know
what they're for:

| Tool                 | Places                   | The signer                           |
| :------------------- | :----------------------- | :----------------------------------- |
| `signer-signature`   | The place they sign      | Draws, types or uploads a signature  |
| `signer-initials`    | A box for their initials | Does the same for their initials     |
| `signer-name`        | Their name               | Types nothing: your app knows it     |
| `signer-email`       | Their email address      | Types nothing                        |
| `signer-date-signed` | The day they signed      | Types nothing: it's written for them |

Each places a field with a [`purpose`](https://www.embedpdf.com/docs/headless/angular/forms/building.md#what-a-field-is-for), required but for the day of
signing. Every other field tool works too, such as a checkbox for "I agree".
[Place fields for a signer](https://www.embedpdf.com/docs/headless/angular/forms/building.md#place-fields-for-a-signer) has a live example, and
[Form tools and signing tools](https://www.embedpdf.com/docs/headless/angular/forms/building.md#form-tools-and-signing-tools) lists every tool.

- **One signature field per signer.** It's the one place their digital signature goes. Their
  initials, and any other place their mark shows, are [image fields](https://www.embedpdf.com/docs/headless/angular/forms/building.md#image-fields),
  which their signature covers.
- **On a scan saved sideways,** turn the page first: fields are placed
  [the way the sender sees it](https://www.embedpdf.com/docs/headless/angular/forms/building.md#on-a-turned-page).
- **Placing fields for other people takes a permission** for each group:
  `fields:set-group:group=buyer`. `form.canSetGroup('buyer')` says whether the sender has it.

When the sender is done, [save the document](https://www.embedpdf.com/docs/headless/angular/documents/saving.md). The fields are in the PDF, with
each one's group, purpose and required flag.

## Open it for a signer

Each signer opens the same document, with who they are and the permissions for their own group.
The signature plugin is in `'finish'` mode, with the key that signs:

**`plugins.ts`**

```typescript
import { Component } from '@angular/core';
import { withForm } from '@embedpdf/angular/form';
import { provideEmbedPdf } from '@embedpdf/angular/runtime';
import { withSignature } from '@embedpdf/angular/signature';
import { signingKey } from './keys';
import { engine } from './pdf';

@Component({
  selector: 'app-signing',
  providers: [
    provideEmbedPdf(
      { engine },
      /* … */
      withForm(),
      // A mark placed in a signature field is drawn in: nothing is sealed until finish().
      withSignature({ signingKey, mode: 'finish' }),
    ),
  ],
  template: `<!-- … -->`,
})
export class Signing {}
```

**`signer-viewer.ts`**

```typescript
import { Component } from '@angular/core';
import { EpdfFormLayer } from '@embedpdf/angular/form';
import { EpdfRenderLayer } from '@embedpdf/angular/render';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage } from '@embedpdf/angular/stage';
import { Guide } from './guide';
import { NextTag } from './next-tag';
import { contract, engine, features } from './setup';

@Component({
  selector: 'app-signer-viewer',
  imports: [
    EpdfDocumentGate,
    EpdfStage,
    EpdfPageTemplate,
    EpdfRenderLayer,
    EpdfFormLayer,
    Guide,
    NextTag,
  ],
  providers: [
    provideEmbedPdf(
      {
        engine,
        identity: { userId: 'u_381', displayName: 'Dana Smith', email: 'dana@example.com' },
        scope: [
          'doc.open',
          'doc.render',
          'doc.forms.read',
          'fields:fill:group=buyer',
          'fields:sign:group=buyer',
        ],
        initialDocuments: [{ source: contract }],
      },
      ...features,
    ),
  ],
  template: `
    <ng-container *epdfDocumentGate>
      <app-guide />
      <epdf-stage>
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-form-layer />
        </ng-template>
        <app-next-tag />
      </epdf-stage>
    </ng-container>
  `,
})
export class SignerViewer {}
```

- **`fields:fill` and `fields:sign` name the group,** so Dana fills in and signs the buyer's fields
  and nothing else. The engine checks every change, so this holds whatever your UI does.
- **`identity` is where her name and email address come from** when a field asks for them.
- **Add `doc.sign` when her signature should be checkable for years.** The validation data and
  the document timestamp belong to the document, not to a group, so they take the document's own
  permission. Beside `fields:sign:group=buyer` it lets her sign no other group's field. See
  [Keep a signature checkable for years](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#keep-a-signature-checkable-for-years).

Every signer sees every field and every value: groups decide who changes a field, not who sees it.

## What the signer sees

With the form layer on the page, and nothing more from you:

- **Their fields stand out** in their color. Other people's fields show as the PDF has them, take
  no input, and Tab skips them.
- **An empty field says what it's for:** "Signature", "Name".
- **What your app knows is filled in when they start.** [`form.prefill()`](https://www.embedpdf.com/docs/headless/angular/forms.md#values-the-app-already-knows)
  writes Dana's name, her email address and today's date into her own empty fields, as real
  values: she sees them, they count as filled in, and she changes them unless the field is
  read-only. Call it when the signer starts, as the guide below does.

The colors and texts are settings: see [Fields for several people](https://www.embedpdf.com/docs/headless/angular/forms.md#fields-for-several-people).

## Guide them to what's left

`validate()` says which required fields are still empty, and `focusNext()` goes to the next one. A
bar with "2 of 5", **Next** and **Finish** is those two calls:

**`guide.ts`**

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

@Component({
  selector: 'app-guide',
  imports: [FinishButton],
  template: `
    <div class="guide">
      {{ check().required.length - check().missing.length }} of {{ check().required.length }}
      <button
        [disabled]="check().missing.length === 0"
        (click)="form.focusNext({ required: true, empty: true, wrap: true })"
      >
        Next
      </button>
      <app-finish-button />
    </div>
  `,
})
export class Guide {
  protected readonly form = inject(EpdfForm);

  protected readonly check = computed(() => {
    this.form.fields(); // again when a field is filled in
    return this.form.validate();
  });

  constructor() {
    // The signer starts: their name, their email address and today's date are written.
    void this.form.prefill();
  }
}
```

- **A signature field counts once it holds a mark,** and the day of signing is never on the
  list: nobody types it.
- **`getFocusedField()`,** or `focusedField` in the form's state, says where the cursor is.
- **The same bar serves a plain form** nobody signs: it reads the form, not the signatures.

To point at the field itself, pin a tag to it. This one sits beside the next field to fill in:

**`next-tag.ts`**

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

/** A tag beside the next required field that is still empty. */
@Component({
  selector: 'app-next-tag',
  imports: [EpdfAnchored],
  template: `
    @if (next(); as field) {
      <epdf-anchored [anchor]="anchor()" placement="left" [gap]="6" pinned>
        <button class="next-tag" (click)="form.focus(field.ref)">
          {{ field.kind === 'signature' ? 'Sign' : 'Fill in' }}
        </button>
      </epdf-anchored>
    }
  `,
})
export class NextTag {
  protected readonly form = inject(EpdfForm);

  protected readonly next = computed(() => {
    this.form.fields(); // again when a field is filled in
    return this.form.validate().missing[0] ?? null;
  });
  protected readonly anchor = this.form.widgetAnchorOf(() => {
    const next = this.next();
    return next ? (this.form.getWidgets(next.ref)[0]?.ref ?? null) : null;
  });
}
```

Put it inside `<epdf-stage>`.
[Your own form controls](https://www.embedpdf.com/docs/headless/angular/forms/controls.md) has more: a calendar next to a date field, a tag on every
signature field, a control of your own.

## Collect the signature

A click on a signature field that isn't signed makes it the
[target](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#sign-here-in-a-form). Show your signature pad, and place what the signer made:

```ts
const field = signature.getTarget();
if (field) {
  // or { assetId }, from their signature library
  await signature.placeMark({ source: png }, { field });
}
```

In `'finish'` mode the mark is drawn into the field and nothing is sealed yet:

- **Another mark takes its place.** A click on the field makes it the target again.
- **`signature.clearField(field)` takes it out,** and the field is on the list of what's left
  again.
- **Each is one step to undo,** with the history plugin.

[A person's signatures](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#a-persons-signatures) keeps a signature and initials to use
again.

## Finish

One call seals the signer's part:

**`finish.ts`**

```typescript
import { Component, inject } from '@angular/core';
import { EpdfForm } from '@embedpdf/angular/form';
import { EpdfSignature } from '@embedpdf/angular/signature';
import { askConsent, showProblems } from './dialogs'; // your own

@Component({
  selector: 'app-finish-button',
  template: `
    <!-- Nothing here is this person's to sign, or they finished already. -->
    @if (signature.canFinish()) {
      <button [disabled]="signature.busy()" (click)="finish()">Finish</button>
    }
  `,
})
export class FinishButton {
  private readonly form = inject(EpdfForm);
  protected readonly signature = inject(EpdfSignature);

  protected async finish() {
    if (!(await askConsent())) return;

    const result = await this.signature.finish();
    if (result.status === 'incomplete') {
      showProblems(result.missing, result.invalid);
      const first = result.missing[0] ?? result.invalid[0]?.field;
      if (first) this.form.focus(first.ref);
    }
  }
}
```

`finish()` does, in this order:

1. **Picks the signer's signature field:** the one they may sign and haven't signed.
2. **Writes the day of signing** into their `date-signed` fields, so a rule of the form that
   reads it is asked with today's date.
3. **Writes what they're still typing,** so a box the cursor hasn't left is part of it.
4. **Checks their fields:** every required one is filled in, every value passes the form's own
   rules, and the signature field holds a mark. If not, nothing is signed and it resolves
   `{ status: 'incomplete' }` with what is `missing` and what is `invalid`.
5. **Asks for your `signingKey`.**
6. **Has the engine prepare the signing.** From here it takes no change, from anyone.
7. **Checks once more,** the form the engine prepared, with what changed while the signer was
   asked for a PIN.
8. **Signs their signature field** with the key, keeping the mark they placed.
9. **Adds the validation data and the document timestamp,** when the plugin has them set.

The signature covers everything up to step 8, the date among it, and locks the signer's group:
every field in it is final, in this viewer and in every other PDF app.

- **Ask for consent before you call it.** What the signer agrees to is your app's text, not the
  viewer's.
- **`canFinish()` says whether there's a field for this person to sign.** It's `false` once they
  finished, and for someone who only looks.
- **The day of signing is the day they finish.** `prefill()` wrote the day they started; a
  signer who comes back later signs today's date.
- **Nothing else is written.** A name they changed stays as they left it, and a field they
  emptied stays empty.

[Sign as the last step](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#sign-as-the-last-step) has every detail: what `finish()`
resolves, what it rejects with, and what the file holds when the key fails.

## The next signer

The engine doesn't order the signers: your server does, by giving the next person their permissions
when the one before is done. The seller then opens the document, sees Dana's fields filled in and
locked, and goes through the same steps for theirs.

When the last one has finished, [every signature can be checked](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#check-the-signatures),
by this viewer and by Acrobat.

## Good to know

### What's in the PDF

| In the PDF, for every app                             | In your app only               |
| :---------------------------------------------------- | :----------------------------- |
| Each field's group, purpose, required flag and format | A group's `label` and `color`  |
| The values, the pictures and the signatures           | The texts an empty field shows |

Another PDF app shows the fields as plain form fields, and checks the signatures as it does any.

### Fill in first, sign once

A signature seals the document as it is. That's why a signer fills in everything and signs last,
with one signature: a field filled in after their signature would be a change to what they signed.

### A form with no groups

One person fills in a form and signs it the same way: `'finish'` mode, a mark, `finish()`. With no
groups, `finish()` locks every field in no group that holds a value, the day of signing among
them. What's still empty stays open, and so does every other signature field: a second person
fills in the rest and signs theirs, and both signatures hold.

To lock everything, say so. The other signature fields are locked then too, so nobody signs
after it:

```ts
await signature.finish({ lock: { action: 'all', fields: [] } });
```

[Sign as the last step](https://www.embedpdf.com/docs/headless/angular/forms/signatures.md#sign-as-the-last-step) says what holds a value, and how a
call names its own lock.

### Without a key

`finish()` needs a `signingKey`. For a flow where a drawn signature is enough, leave the signature
plugin in `'visual'` mode and use `form.validateValues()` and `form.prefill()` yourself; see
[Check the values too](https://www.embedpdf.com/docs/headless/angular/forms.md#check-the-values-too) and
[Values the app already knows](https://www.embedpdf.com/docs/headless/angular/forms.md#values-the-app-already-knows).

### Turn pages before the first signature

A page turned after someone signed is a change to a signed document. Turn scanned pages upright
while the sender prepares the document.
