---
title: "A signing flow — Vue"
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: "Vue"
other_frameworks:
  "React": "https://www.embedpdf.com/docs/headless/react/forms/signing-flow.md"
  "Svelte": "https://www.embedpdf.com/docs/headless/svelte/forms/signing-flow.md"
  "Angular": "https://www.embedpdf.com/docs/headless/angular/forms/signing-flow.md"
source: "https://www.embedpdf.com/docs/headless/vue/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/vue/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/vue/forms/signatures.md#check-the-signatures)      |

**`App.vue`**

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { interactionPlugin } from '@embedpdf/vue/interaction';
import { FormLayer, formPlugin } from '@embedpdf/vue/form';
import { signaturePlugin } from '@embedpdf/vue/signature';
import { localEngine } from '@embedpdf/engine';
import { keys, people, type Person } from './people';
import HandOver from './HandOver.vue';
import SignCard from './SignCard.vue';
import Toolbar from './Toolbar.vue';

import '../signing-flow.css';

const engine = localEngine();
const plugins = [
  stagePlugin(),
  renderPlugin(),
  interactionPlugin(),
  formPlugin(),
  signaturePlugin({
    // 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),
    },
  }),
];

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

const person = ref<Person>('sender');
const next = () => (person.value = person.value === 'sender' ? 'borrower' : 'approver');
</script>

<template>
  <Viewer
    :engine="engine"
    :plugins="plugins"
    :scope="people[person].scope"
    :identity="people[person].identity"
    :initial-documents="[{ source: loan, name: 'equipment-loan.pdf' }]"
  >
    <HandOver :person="person" />
    <DocumentGate>
      <template #fallback><p class="loading">Opening…</p></template>
      <Toolbar :person="person" @next="next" />
      <Stage class="stage">
        <template #page>
          <RenderLayer />
          <FormLayer />
        </template>
        <template #overlay>
          <SignCard />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

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

**`Guide.vue`**

```vue
<!-- 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()`. -->
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useForm, useFormState } from '@embedpdf/vue/form';
import type { FormField } from '@embedpdf/vue/form';
import { useSignature, useSignatureState } from '@embedpdf/vue/signature';
import { keys, people, signers, type Signer } from './people';

// The last signer hands the form over to no one.
const props = defineProps<{ person: Signer; last: boolean }>();
const emit = defineEmits<{ handOver: [] }>();

const form = useForm();
const signature = useSignature();
const { fields } = useFormState();
const { busy, signatures } = useSignatureState();
const agreed = ref(false);
const problems = ref<string[]>([]);

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

// What Finish said is left stands until the form changes.
watch(fields, () => (problems.value = []));

const check = computed(() => {
  void fields.value; // again when a field is filled in
  return form.validate();
});

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

// 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.
const finish = async () => {
  const result = await signature.finish({
    signingKey: () => keys[props.person],
    signer: { reason: 'I agree to the terms of this loan' },
  });
  if (result.status === 'signed') {
    problems.value = [];
    return;
  }
  problems.value = [
    ...result.missing.map(nameOf),
    ...result.invalid.map(({ field, message }) => `${nameOf(field)}: ${message ?? 'not valid'}`),
  ];
  form.focus((result.missing[0] ?? result.invalid[0]!.field).ref);
};
</script>

<template>
  <!-- Nothing left for this person to sign: they finished, and their fields are final. -->
  <div v-if="!signature.canFinish()" class="toolbar">
    <output class="readout">
      {{
        signatures
          .map((each) => `${each.signer?.name}: ${each.verdict?.summary ?? 'checking…'}`)
          .join(' · ')
      }}
    </output>
    <button v-if="!last" type="button" class="button" @click="emit('handOver')">
      Hand over to Ada Lovelace
    </button>
  </div>
  <div v-else class="toolbar">
    <span class="legend">
      <i
        class="swatch"
        :style="{ background: signers.find((each) => each.id === person)?.color }"
      />{{ people[person].name }}
    </span>
    <output class="readout">
      {{ `${check.required.length - check.missing.length} of ${check.required.length} filled in` }}
    </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" />
    <label class="consent">
      <input v-model="agreed" type="checkbox" />
      I agree to sign electronically
    </label>
    <button type="button" class="button" :disabled="!agreed || busy" @click="finish">Finish</button>
    <output v-if="problems.length > 0" class="problems">
      Still to do: {{ problems.join(', ') }}
    </output>
  </div>
</template>
```

**`HandOver.vue`**

```vue
<!-- A document keeps who it opened for, so the next person opens the saved form again. -->
<script setup lang="ts">
import { watch } from 'vue';
import { useDocument, useDocuments } from '@embedpdf/vue/runtime';
import type { Person } from './people';

const props = defineProps<{ person: Person }>();

const documents = useDocuments();
const { id } = useDocument();

let opened = props.person;
watch([() => props.person, id], async ([person, current]) => {
  if (person === opened || !current) return;
  opened = person;
  const bytes = await documents.download();
  await documents.close(current);
  await documents.open({ kind: 'bytes', bytes }, { name: 'equipment-loan.pdf' });
});
</script>

<template></template>
```

**`people.ts`**

```typescript
import type { PageRef } from '@embedpdf/vue/runtime';
import type { FormFieldDraft } from '@embedpdf/vue/form';
import { createTestSigner } from '@embedpdf/vue/signature';

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

// Who the document's groups are: your app's own list. The PDF holds only each field's group id.
export 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'];

export 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' },
  },
};

export type Person = keyof typeof people;
export 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 };

export 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),
  ];
};
```

**`Prepare.vue`**

```vue
<!-- 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. -->
<script setup lang="ts">
import { watch } from 'vue';
import { usePageList } from '@embedpdf/vue/runtime';
import { useForm } from '@embedpdf/vue/form';
import { fieldsOn } from './people';

const emit = defineEmits<{ done: [] }>();

const form = useForm();
const pages = usePageList();

let started = false;
watch(
  () => pages.value[0]?.ref, // the printed form
  async (page) => {
    if (!page || started) return;
    started = true;
    for (const draft of fieldsOn(page)) await form.create(draft);
    emit('done');
  },
  { immediate: true },
);
</script>

<template>
  <div class="toolbar">
    <output class="readout">The sender is placing the fields…</output>
  </div>
</template>
```

**`SignCard.vue`**

```vue
<!-- 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. -->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { Anchored } from '@embedpdf/vue/anchored';
import { useForm, useFormWidgetAnchor } from '@embedpdf/vue/form';
import { useSignature, useSignatureState } from '@embedpdf/vue/signature';

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

const form = useForm();
const signature = useSignature();
const { target } = useSignatureState();
const row = computed(() => (target.value ? form.getWidgets(target.value)[0] : undefined));
const anchor = useFormWidgetAnchor(() => row.value?.ref ?? null);
const card = ref<HTMLDivElement | null>(null);
const pad = ref<HTMLCanvasElement | null>(null);
const drawn = ref(false);
let last: Point | null = null;

// Each field starts with an empty pad, and the card takes the cursor, so Escape closes it.
watch(
  [target, card],
  () => {
    last = null;
    drawn.value = false;
    pad.value?.getContext('2d')?.clearRect(0, 0, pad.value.width, pad.value.height);
    if (target.value) card.value?.focus();
  },
  { flush: 'post' },
);

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

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

const draw = (event: PointerEvent) => {
  const canvas = event.currentTarget as HTMLCanvasElement;
  const from = last;
  const ink = canvas.getContext('2d');
  if (!from || !ink || !canvas.hasPointerCapture(event.pointerId)) return;
  const to = pointOf(event, canvas);
  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();
  drawn.value = true;
};

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

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

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

<template>
  <Anchored v-if="target" :anchor="anchor" placement="bottom-start" :gap="8">
    <div
      ref="card"
      class="sign-card"
      role="dialog"
      aria-label="Draw your signature"
      tabindex="-1"
      @keydown.esc="close"
    >
      <canvas
        ref="pad"
        class="sign-pad"
        width="240"
        height="100"
        @pointerdown="start"
        @pointermove="draw"
      />
      <div class="sign-actions">
        <button v-if="row?.hasMark" 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">
          {{ row?.hasMark ? 'Replace' : 'Place' }}
        </button>
      </div>
    </div>
  </Anchored>
</template>
```

**`Toolbar.vue`**

```vue
<script setup lang="ts">
import { useForm } from '@embedpdf/vue/form';
import { signers, type Person } from './people';
import Guide from './Guide.vue';
import Prepare from './Prepare.vue';

defineProps<{ person: Person }>();
const emit = defineEmits<{ next: [] }>();

// The open document says what its user may do: it is the sender's while they may design it.
const form = useForm();

// Tell the open document who its groups are.
form.setGroups(signers);
</script>

<template>
  <Prepare v-if="form.canDesign()" @done="emit('next')" />
  <Guide
    v-else-if="person !== 'sender'"
    :person="person"
    :last="person === 'approver'"
    @hand-over="emit('next')"
  />
</template>
```

> **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.vue`**

```vue
<!-- Render it where the document shows, so every document you open gets its own list. -->
<script setup lang="ts">
import { watchEffect } from 'vue';
import { useForm, type FormGroupInput } from '@embedpdf/vue/form';

const props = defineProps<{ signers: FormGroupInput[] }>();
const form = useForm();

watchEffect(() => form.setGroups(props.signers));
</script>

<template></template>
```

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/vue/forms.md#fields-for-several-people) has every detail.

## The sender places the fields

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

**`sender-toolbar.vue`**

```vue
<script setup lang="ts">
import { useForm, useFormState } from '@embedpdf/vue/form';
import { useInteraction, useInteractionState } from '@embedpdf/vue/interaction';

const FIELD_TOOLS = [
  ['form-text', 'Text'],
  ['form-checkbox', 'Checkbox'],
  ['signer-signature', 'Signature'],
] as const;

const form = useForm();
const { groups, designGroup } = useFormState();
const interaction = useInteraction();
const { activeToolId } = useInteractionState();
</script>

<template>
  <button
    v-for="group in groups"
    :key="group.id"
    :aria-pressed="designGroup === group.id"
    :disabled="!form.canSetGroup(group.id)"
    @click="form.setDesignGroup(group.id)"
  >
    <i :style="{ background: group.color }" /> {{ group.label ?? group.id }}
  </button>

  <button
    v-for="[id, label] in FIELD_TOOLS"
    :key="id"
    :aria-pressed="activeToolId === id"
    @click="interaction.activateTool(id)"
  >
    {{ label }}
  </button>
</template>
```

`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/vue/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/vue/forms/building.md#place-fields-for-a-signer) has a live example, and
[Form tools and signing tools](https://www.embedpdf.com/docs/headless/vue/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/vue/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/vue/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/vue/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 { formPlugin } from '@embedpdf/vue/form';
import { signaturePlugin } from '@embedpdf/vue/signature';
import { signingKey } from './keys';

export const plugins = [
  /* … */
  formPlugin(),
  // A mark placed in a signature field is drawn in: nothing is sealed until finish().
  signaturePlugin({ signingKey, mode: 'finish' }),
];
```

**`signer-viewer.vue`**

```vue
<script setup lang="ts">
import { FormLayer } from '@embedpdf/vue/form';
import { RenderLayer } from '@embedpdf/vue/render';
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import { Stage } from '@embedpdf/vue/stage';
import Guide from './guide.vue';
import NextTag from './next-tag.vue';
import { contract, engine, plugins } from './setup';
</script>

<template>
  <Viewer
    :engine="engine"
    :plugins="plugins"
    :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',
    ]"
    :initial-documents="[{ source: contract }]"
  >
    <DocumentGate>
      <Guide />
      <Stage>
        <template #page>
          <RenderLayer />
          <FormLayer />
        </template>
        <template #overlay>
          <NextTag />
        </template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

- **`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/vue/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/vue/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/vue/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.vue`**

```vue
<!-- guide.vue -->
<script setup lang="ts">
import { computed, onMounted } from 'vue';
import { useForm, useFormState } from '@embedpdf/vue/form';
import FinishButton from './finish.vue';

const form = useForm();
const { fields } = useFormState();

const check = computed(() => {
  void fields.value; // again when a field is filled in
  return form.validate();
});

// The signer starts: their name, their email address and today's date are written.
onMounted(() => void form.prefill());
</script>

<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>
    <FinishButton />
  </div>
</template>
```

- **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.vue`**

```vue
<!-- next-tag.vue -->
<script setup lang="ts">
import { computed } from 'vue';
import { Anchored } from '@embedpdf/vue/anchored';
import { useForm, useFormState, useFormWidgetAnchor } from '@embedpdf/vue/form';

const form = useForm();
const { fields } = useFormState();

// The next required field that is still empty.
const next = computed(() => {
  void fields.value; // again when a field is filled in
  return form.validate().missing[0] ?? null;
});
const anchor = useFormWidgetAnchor(() =>
  next.value ? (form.getWidgets(next.value.ref)[0]?.ref ?? null) : null,
);
</script>

<template>
  <Anchored v-if="next" :anchor="anchor" placement="left" :gap="6" pinned>
    <button class="next-tag" @click="form.focus(next.ref)">
      {{ next.kind === 'signature' ? 'Sign' : 'Fill in' }}
    </button>
  </Anchored>
</template>
```

Mount it in the Stage's `#overlay` slot.
[Your own form controls](https://www.embedpdf.com/docs/headless/vue/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/vue/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/vue/forms/signatures.md#a-persons-signatures) keeps a signature and initials to use
again.

## Finish

One call seals the signer's part:

**`finish.vue`**

```vue
<!-- finish.vue -->
<script setup lang="ts">
import { useForm } from '@embedpdf/vue/form';
import { useSignature, useSignatureState } from '@embedpdf/vue/signature';
import { askConsent, showProblems } from './dialogs'; // your own

const form = useForm();
const signature = useSignature();
const { busy } = useSignatureState();

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

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

<template>
  <!-- Nothing here is this person's to sign, or they finished already. -->
  <button v-if="signature.canFinish()" :disabled="busy" @click="finish">Finish</button>
</template>
```

`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/vue/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/vue/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/vue/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/vue/forms.md#check-the-values-too) and
[Values the app already knows](https://www.embedpdf.com/docs/headless/vue/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.
