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…

import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import {
  Viewer,
  DocumentGate,
  useDocument,
  useDocuments,
  usePageList,
} from '@embedpdf/react/runtime';
import type { OpenInput, PageRef } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { Anchored } from '@embedpdf/react/anchored';
import {
  FormLayer,
  formPlugin,
  useForm,
  useFormState,
  useFormWidgetAnchor,
} from '@embedpdf/react/form';
import type { FormField, FormFieldDraft } from '@embedpdf/react/form';
import {
  createTestSigner,
  signaturePlugin,
  useSignature,
  useSignatureState,
} from '@embedpdf/react/signature';
import { localEngine } from '@embedpdf/engine';

import './signing-flow.css';

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

// 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.
 */
function Prepare({ onDone }: { onDone: () => void }) {
  const form = useForm();
  const page = usePageList()[0]?.ref;
  const started = useRef(false);

  useEffect(() => {
    if (!page || started.current) return;
    started.current = true;
    void (async () => {
      for (const draft of fieldsOn(page)) await form.create(draft);
      onDone();
    })();
  }, [form, page, onDone]);

  return (
    <div className="toolbar">
      <output className="readout">The sender is placing the fields…</output>
    </div>
  );
}

// A document keeps who it opened for, so the next person opens the saved form again.
function HandOver({ person }: { person: Person }) {
  const documents = useDocuments();
  const { id } = useDocument();
  const opened = useRef(person);

  useEffect(() => {
    if (person === opened.current || !id) return;
    opened.current = person;
    void (async () => {
      const bytes = await documents.download();
      await documents.close(id);
      await documents.open({ kind: 'bytes', bytes }, { name: 'equipment-loan.pdf' });
    })();
  }, [person, id, documents]);
  return null;
}

/** 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()`.
 */
function Guide({ person, onHandOver }: { person: Signer; onHandOver: (() => void) | null }) {
  const form = useForm();
  const signature = useSignature();
  const fields = useFormState((state) => state.fields); // again when a field is filled in
  const { busy, signatures } = useSignatureState();
  const [agreed, setAgreed] = useState(false);
  const [problems, setProblems] = useState<string[]>([]);

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

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

  const { required, missing } = form.validate();

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

  // Nothing left for this person to sign: they finished, and their fields are final.
  if (!signature.canFinish()) {
    return (
      <div className="toolbar">
        <output className="readout">
          {signatures
            .map((each) => `${each.signer?.name}: ${each.verdict?.summary ?? 'checking…'}`)
            .join(' · ')}
        </output>
        {onHandOver && (
          <button type="button" className="button" onClick={onHandOver}>
            Hand over to Ada Lovelace
          </button>
        )}
      </div>
    );
  }

  return (
    <div className="toolbar">
      <span className="legend">
        <i
          className="swatch"
          style={{ background: signers.find((each) => each.id === person)?.color }}
        />
        {people[person].name}
      </span>
      <output className="readout">
        {required.length - missing.length} of {required.length} filled in
      </output>
      <button
        type="button"
        className="button"
        disabled={missing.length === 0}
        onClick={() => form.focusNext({ required: true, empty: true, wrap: true })}
      >
        Next
      </button>
      <span className="divider" />
      <label className="consent">
        <input
          type="checkbox"
          checked={agreed}
          onChange={(event) => setAgreed(event.target.checked)}
        />
        I agree to sign electronically
      </label>
      <button type="button" className="button" disabled={!agreed || busy} onClick={finish}>
        Finish
      </button>
      {problems.length > 0 && (
        <output className="problems">Still to do: {problems.join(', ')}</output>
      )}
    </div>
  );
}

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.
 */
function SignCard() {
  const form = useForm();
  const signature = useSignature();
  const { target } = useSignatureState();
  const row = target ? form.getWidgets(target)[0] : undefined;
  const anchor = useFormWidgetAnchor(row?.ref ?? null);
  const card = useRef<HTMLDivElement>(null);
  const pad = useRef<HTMLCanvasElement>(null);
  const last = useRef<Point | null>(null);
  const [drawn, setDrawn] = useState(false);

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

  if (!target) return null;

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

  const start = (event: React.PointerEvent<HTMLCanvasElement>) => {
    event.currentTarget.setPointerCapture(event.pointerId);
    last.current = pointOf(event);
  };

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

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

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

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

  return (
    <Anchored anchor={anchor} placement="bottom-start" gap={8}>
      <div
        ref={card}
        className="sign-card"
        role="dialog"
        aria-label="Draw your signature"
        tabIndex={-1}
        onKeyDown={(event) => event.key === 'Escape' && close()}
      >
        {/* Anchored UI keeps a press from reaching the page under it, before React hears it:
            the pad listens while the press is on its way down. */}
        <canvas
          ref={pad}
          className="sign-pad"
          width={240}
          height={100}
          onPointerDownCapture={start}
          onPointerMove={draw}
        />
        <div className="sign-actions">
          {row?.hasMark && (
            <button type="button" className="button" onClick={remove}>
              Remove
            </button>
          )}
          <button type="button" className="button" onClick={close}>
            Cancel
          </button>
          <button type="button" className="button" disabled={!drawn} onClick={place}>
            {row?.hasMark ? 'Replace' : 'Place'}
          </button>
        </div>
      </div>
    </Anchored>
  );
}

function Toolbar({ person, onNext }: { person: Person; onNext: () => void }) {
  const form = useForm();

  // Tell the open document who its groups are, before the first paint.
  useLayoutEffect(() => {
    form.setGroups(signers);
  }, [form]);

  // The open document says what its user may do: it is the sender's while they may design it.
  if (form.canDesign()) return <Prepare onDone={onNext} />;
  if (person === 'sender') return null;
  return <Guide person={person} onHandOver={person === 'borrower' ? onNext : null} />;
}

export default function App() {
  const [person, setPerson] = useState<Person>('sender');
  const next = () => setPerson((current) => (current === 'sender' ? 'borrower' : 'approver'));

  return (
    <Viewer
      engine={engine}
      plugins={plugins}
      scope={people[person].scope}
      identity={people[person].identity}
      initialDocuments={[{ source: loan, name: 'equipment-loan.pdf' }]}
    >
      <HandOver person={person} />
      <DocumentGate fallback={<p className="loading">Opening…</p>}>
        <Toolbar person={person} onNext={next} />
        <Stage className="stage" overlay={<SignCard />}>
          {() => (
            <>
              <RenderLayer />
              <FormLayer />
            </>
          )}
        </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.tsx
import { useLayoutEffect } from 'react';
import { useForm, type FormGroupInput } from '@embedpdf/react/form';

/** Render it where the document shows, so every document you open gets its own list. */
export function Signers({ signers }: { signers: FormGroupInput[] }) {
  const form = useForm();

  // Before the first paint, so no field shows in another color first.
  useLayoutEffect(() => {
    form.setGroups(signers);
  }, [form, signers]);

  return null;
}

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.tsx
import { useForm, useFormState } from '@embedpdf/react/form';
import { useInteraction, useInteractionState } from '@embedpdf/react/interaction';

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

export function SenderToolbar() {
  const form = useForm();
  const { groups, designGroup } = useFormState();
  const interaction = useInteraction();
  const { activeToolId } = useInteractionState();

  return (
    <>
      {groups.map((group) => (
        <button
          key={group.id}
          aria-pressed={designGroup === group.id}
          disabled={!form.canSetGroup(group.id)}
          onClick={() => form.setDesignGroup(group.id)}
        >
          <i style={{ background: group.color }} /> {group.label ?? group.id}
        </button>
      ))}

      {FIELD_TOOLS.map(([id, label]) => (
        <button
          key={id}
          aria-pressed={activeToolId === id}
          onClick={() => interaction.activateTool(id)}
        >
          {label}
        </button>
      ))}
    </>
  );
}

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/react/form';
import { signaturePlugin } from '@embedpdf/react/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.tsx
import { FormLayer } from '@embedpdf/react/form';
import { RenderLayer } from '@embedpdf/react/render';
import { DocumentGate, Viewer } from '@embedpdf/react/runtime';
import { Stage } from '@embedpdf/react/stage';
import { Guide } from './guide';
import { NextTag } from './next-tag';
import { contract, engine, plugins } from './setup';

export function SignerViewer() {
  return (
    <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',
      ]}
      initialDocuments={[{ source: contract }]}
    >
      <DocumentGate>
        <Guide />
        <Stage overlay={<NextTag />}>
          {() => (
            <>
              <RenderLayer />
              <FormLayer />
            </>
          )}
        </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.tsx
import { useEffect } from 'react';
import { useForm, useFormState } from '@embedpdf/react/form';
import { FinishButton } from './finish';

export function Guide() {
  const form = useForm();
  useFormState((state) => state.fields); // again when a field is filled in
  const { required, missing } = form.validate();

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

  return (
    <div className="guide">
      {required.length - missing.length} of {required.length}
      <button
        disabled={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.tsx
import { Anchored } from '@embedpdf/react/anchored';
import { useForm, useFormState, useFormWidgetAnchor } from '@embedpdf/react/form';

/** A tag beside the next required field that is still empty. */
export function NextTag() {
  const form = useForm();
  useFormState((state) => state.fields); // again when a field is filled in
  const next = form.validate().missing[0];
  const anchor = useFormWidgetAnchor(next ? (form.getWidgets(next.ref)[0]?.ref ?? null) : null);

  if (!next) return null;
  return (
    <Anchored anchor={anchor} placement="left" gap={6} pinned>
      <button className="next-tag" onClick={() => form.focus(next.ref)}>
        {next.kind === 'signature' ? 'Sign' : 'Fill in'}
      </button>
    </Anchored>
  );
}

Mount it in the Stage’s overlay. 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.tsx
import { useForm } from '@embedpdf/react/form';
import { useSignature, useSignatureState } from '@embedpdf/react/signature';
import { askConsent, showProblems } from './dialogs'; // your own

export function FinishButton() {
  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);
    }
  }

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

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.