EmbedPDF

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:

WhoDoesUses
The senderPlaces each signer’s fields on the documentDesign mode, with the signers listed
Each signerFills in their own fields and signsThe form layer, with permissions for their own fields
Anyone, laterChecks who signed, and that nothing changedCheck the signatures

Loading live preview…

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

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

<script lang="ts">
  let person = $state<Person>('sender');
  const next = () => (person = person === 'sender' ? 'borrower' : 'approver');
</script>

<Viewer
  {engine}
  {plugins}
  scope={people[person].scope}
  identity={people[person].identity}
  initialDocuments={[{ source: loan, name: 'equipment-loan.pdf' }]}
>
  <HandOver {person} />
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Opening…</p>
    {/snippet}
    <Toolbar {person} onNext={next} />
    <Stage class="stage">
      <RenderLayer />
      <FormLayer />
      {#snippet overlay()}
        <SignCard />
      {/snippet}
    </Stage>
  </DocumentGate>
</Viewer>

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. 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.svelte
<!-- Render it where the document shows, so every document you open gets its own list. -->
<script lang="ts">
  import { useForm, type FormGroupInput } from '@embedpdf/svelte/form';

  let { signers }: { signers: FormGroupInput[] } = $props();

  const form = useForm();

  $effect.pre(() => form.setGroups(signers));
</script>

Give the sender’s page and each signer’s the same list, and everyone sees the same colors. Fields for several people has every detail.

The sender places the fields#

In design mode the sender picks who the next fields are for, then a tool, and clicks on the page:

sender-toolbar.svelte
<script lang="ts">
  import { useForm, useFormState } from '@embedpdf/svelte/form';
  import { useInteraction, useInteractionState } from '@embedpdf/svelte/interaction';

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

  const form = useForm();
  const formState = useFormState();
  const interaction = useInteraction();
  const interactionState = useInteractionState();
</script>

{#each formState.groups as group (group.id)}
  <button
    aria-pressed={formState.designGroup === group.id}
    disabled={!form.canSetGroup(group.id)}
    onclick={() => form.setDesignGroup(group.id)}
  >
    <i style:background={group.color}></i>
    {group.label ?? group.id}
  </button>
{/each}

{#each FIELD_TOOLS as [id, label] (id)}
  <button
    aria-pressed={interactionState.activeToolId === id}
    onclick={() => interaction.activateTool(id)}
  >
    {label}
  </button>
{/each}

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

ToolPlacesThe signer
signer-signatureThe place they signDraws, types or uploads a signature
signer-initialsA box for their initialsDoes the same for their initials
signer-nameTheir nameTypes nothing: your app knows it
signer-emailTheir email addressTypes nothing
signer-date-signedThe day they signedTypes nothing: it’s written for them

Each places a field with a purpose, 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 has a live example, and 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, which their signature covers.
  • On a scan saved sideways, turn the page first: fields are placed the way the sender sees it.
  • 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. 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
import { formPlugin } from '@embedpdf/svelte/form';
import { signaturePlugin } from '@embedpdf/svelte/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.svelte
<script lang="ts">
  import { FormLayer } from '@embedpdf/svelte/form';
  import { RenderLayer } from '@embedpdf/svelte/render';
  import { DocumentGate, Viewer } from '@embedpdf/svelte/runtime';
  import { Stage } from '@embedpdf/svelte/stage';
  import Guide from './guide.svelte';
  import NextTag from './next-tag.svelte';
  import { contract, engine, plugins } from './setup';
</script>

<Viewer
  {engine}
  {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',
  ]}
  initialDocuments={[{ source: contract }]}
>
  <DocumentGate>
    <Guide />
    <Stage>
      <RenderLayer />
      <FormLayer />
      {#snippet overlay()}
        <NextTag />
      {/snippet}
    </Stage>
  </DocumentGate>
</Viewer>
  • 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.

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() 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.

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.svelte
<!-- guide.svelte -->
<script lang="ts">
  import { onMount } from 'svelte';
  import { useForm, useFormState } from '@embedpdf/svelte/form';
  import FinishButton from './finish.svelte';

  const form = useForm();
  const formState = useFormState();

  const check = $derived.by(() => {
    void formState.fields; // again when a field is filled in
    return form.validate();
  });

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

<div class="guide">
  {check.required.length - check.missing.length} of {check.required.length}
  <button
    disabled={check.missing.length === 0}
    onclick={() => form.focusNext({ required: true, empty: true, wrap: true })}
  >
    Next
  </button>
  <FinishButton />
</div>
  • 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.svelte
<!-- next-tag.svelte -->
<script lang="ts">
  import { Anchored } from '@embedpdf/svelte/anchored';
  import { useForm, useFormState, useFormWidgetAnchor } from '@embedpdf/svelte/form';

  const form = useForm();
  const formState = useFormState();

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

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

Mount it in the Stage’s overlay snippet. Your own form controls 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. Show your signature pad, and place what the signer made:

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 keeps a signature and initials to use again.

Finish#

One call seals the signer’s part:

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

  const form = useForm();
  const signature = useSignature();
  const signatureState = 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>

<!-- Nothing here is this person's to sign, or they finished already. -->
{#if signature.canFinish()}
  <button disabled={signatureState.busy} onclick={finish}>Finish</button>
{/if}

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 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, by this viewer and by Acrobat.

Good to know#

What’s in the PDF#

In the PDF, for every appIn your app only
Each field’s group, purpose, required flag and formatA group’s label and color
The values, the pictures and the signaturesThe 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:

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

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 and 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.

Was this page helpful?

Your feedback goes directly to the documentation team.