EmbedPDF

Signatures

A digital signature has two parts: the mark, what people see in the signature field, such as a drawn signature; and the key, which seals the document so any later change shows. The signature plugin signs with both, checks the signatures a document already has, and warns before an edit would break one.

Register signaturePlugin() next to formPlugin() and stampPlugin(), with the key to sign with:

Loading live preview…

import { useEffect, useRef, useState } from 'react';
import { Viewer, DocumentGate, usePageList } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin, useStage } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { FormLayer, formPlugin, useForm, useFormState } from '@embedpdf/react/form';
import { stampPlugin, useStamp, useStampAssetPreviewUrl } from '@embedpdf/react/stamp';
import {
  createTestSigner,
  signaturePlugin,
  useSignature,
  useSignatureState,
  useSignerRows,
} from '@embedpdf/react/signature';
import { localEngine } from '@embedpdf/engine';

import './basic.css';

const engine = localEngine();
const assetEngine = engine; // a person's marks are stamps, kept as PDFs; they open here too
// A throwaway key for the demo. Bring your own with `webCryptoSigner`, a
// service with `remoteSigner`, or a person's own with `personalSigner`.
const signer = createTestSigner({ commonName: 'Ada Lovelace' });
const plugins = [
  stagePlugin(),
  renderPlugin(),
  interactionPlugin(),
  formPlugin(),
  stampPlugin({ assetEngine }),
  signaturePlugin({
    key: () => signer,
    // Trust the demo key itself, so its signatures check out as 'valid'.
    trust: { anchors: async () => [(await signer).certificate] },
  }),
];

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

/**
 * The ebook has no signature field, and the browser holds no signatures yet:
 * add a field to the last page, and one person with a typed signature.
 */
function useSetUp() {
  const form = useForm();
  const stamp = useStamp();
  const stage = useStage();
  const status = useFormState((state) => state.status);
  const page = usePageList().at(-1)?.ref;
  const done = useRef(false);

  useEffect(() => {
    if (status !== 'ready' || !page || done.current) return;
    done.current = true;
    void (async () => {
      await form.create({
        family: 'signature',
        name: 'approval',
        widgets: [{ page, rect: { x: 72, y: 560, width: 220, height: 64 }, color: '#94a3b8' }],
      });
      stage.goToPage(page);
      const { library } = await stamp.createLibrary('Ada Lovelace', { kind: 'signatures' });
      await stamp.createAsset({
        libraryId: library.id,
        name: 'signature',
        label: 'Signature',
        mark: { kind: 'text', text: 'Ada Lovelace', fontFamily: 'times-italic', color: '#1d2b53' },
      });
    })();
  }, [form, stamp, stage, status, page]);
}

function MarkButton({ assetId, label, onPick }: { assetId: string; label: string; onPick: () => void }) {
  const url = useStampAssetPreviewUrl(assetId);
  return (
    <button type="button" className="button" title={label} onClick={onPick}>
      {url ? <img src={url} alt={label} className="preview" /> : label}
    </button>
  );
}

function SignBar() {
  useSetUp();
  const signature = useSignature();
  const [person] = useSignerRows();
  const { signatures, target, busy } = useSignatureState();
  const field = useFormState((state) => state.fields.find((candidate) => candidate.family === 'signature'));
  const [error, setError] = useState<string | null>(null);
  const signed = signatures[0];

  // The target is the field someone clicked; without one, the form's signature field.
  const sign = (assetId: string) => {
    const destination = target ?? field?.ref;
    if (!destination) return;
    setError(null);
    signature
      .placeMark({ assetId }, { field: destination })
      .catch((reason: Error) => setError(reason.message));
  };

  let status = 'Click the field, or pick the signature';
  if (!person || !field) status = 'Getting ready…';
  else if (error) status = error;
  else if (busy) status = 'Signing…';
  else if (signed) status = `Signed by ${signed.signer.name}: ${signed.verdict?.summary ?? 'checking…'}`;
  else if (target) status = 'Now pick the signature';

  return (
    <div className="toolbar">
      {person?.signatures.map((asset) => (
        <MarkButton key={asset.id} assetId={asset.id} label={asset.label} onPick={() => sign(asset.id)} />
      ))}
      <output className="readout">{status}</output>
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: ebook }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <SignBar />
        <Stage className="stage">
          {() => (
            <>
              <RenderLayer />
              {/* An empty signature field is "sign here": a click makes it the target */}
              <FormLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}
signature-plugin.ts
import { formPlugin } from '@embedpdf/react/form';
import { indexedDbKeyStore, personalSigner, signaturePlugin } from '@embedpdf/react/signature';
import { stampPlugin } from '@embedpdf/react/stamp';
import { rootCertificate } from './certificates';

export const plugins = [
  /* … */
  formPlugin(),
  stampPlugin(),
  signaturePlugin({
    key: () => personalSigner({ subject: 'Ada Lovelace', store: indexedDbKeyStore('my-app-keys') }),
    trust: { anchors: async () => [rootCertificate] }, // the certificates you trust
  }),
];

Sign a field#

const { version } = await signature.sign({
  field: toFieldRef('approval'),
  mark: { assetId },
  signer: { reason: 'Approved', location: 'Amsterdam' },
});

The mark becomes what the field shows, the key seals the document, and the signed document is saved as a new version. If anything fails along the way, nothing is left half-signed.

A mark is a stamp from a person’s signature library, or image bytes you bring:

{ assetId } // a stamp, drawn, typed or uploaded; see "A person's signatures" below
{ source: pngBytes } // a PNG, a JPEG, or a one-page PDF

Let people click to sign#

People can also arm their signature and click where it goes, as in Preview. With the stamp plugin, arm a mark from a signature library:

  • over an empty signature field, the click signs it;
  • over a signed field, nothing happens;
  • anywhere else, the mark is placed as a stamp.

placeMark() does the same from code:

await signature.placeMark({ assetId }, { field: toFieldRef('approval') }); // signs the field
await signature.placeMark({ assetId }, { page: page.ref, center: { x: 120, y: 90 } }); // a stamp

What happens in a field depends on mode: 'sign' signs it, 'visual' only draws the mark in, and 'ask' asks your UI first through onSignRequested, so you can show your own sign dialog.

Loading live preview…

import { useEffect, useRef } from 'react';
import { Viewer, DocumentGate, usePageList } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin, useStage } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { AnnotationLayer, annotationPlugin } from '@embedpdf/react/annotation';
import { FormLayer, formPlugin, useForm, useFormState } from '@embedpdf/react/form';
import { stampPlugin, useStamp, useStampState } from '@embedpdf/react/stamp';
import {
  createTestSigner,
  signaturePlugin,
  useSignatureState,
  useSignerRows,
} from '@embedpdf/react/signature';
import { localEngine } from '@embedpdf/engine';

import './click-to-sign.css';

const engine = localEngine();
const assetEngine = engine; // a person's marks are stamps, kept as PDFs; they open here too
const signer = createTestSigner({ commonName: 'Ada Lovelace' });
const plugins = [
  stagePlugin(),
  renderPlugin(),
  interactionPlugin(),
  annotationPlugin(),
  formPlugin(),
  stampPlugin({ assetEngine }),
  signaturePlugin({ key: () => signer }),
];

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

/** On load: a signature field on the last page, and a person's signature, armed. */
function useSetUp() {
  const form = useForm();
  const stamp = useStamp();
  const stage = useStage();
  const status = useFormState((state) => state.status);
  const page = usePageList().at(-1)?.ref;
  const done = useRef(false);

  useEffect(() => {
    if (status !== 'ready' || !page || done.current) return;
    done.current = true;
    void (async () => {
      await form.create({
        family: 'signature',
        name: 'approval',
        widgets: [{ page, rect: { x: 72, y: 560, width: 220, height: 64 }, color: '#94a3b8' }],
      });
      stage.goToPage(page);
      const { library } = await stamp.createLibrary('Ada Lovelace', { kind: 'signatures' });
      const { asset } = await stamp.createAsset({
        libraryId: library.id,
        name: 'signature',
        label: 'Signature',
        mark: { kind: 'text', text: 'Ada Lovelace', fontFamily: 'times-italic', color: '#1d2b53' },
      });
      await stamp.armAsset(asset.id, { targetWidth: 160 });
    })();
  }, [form, stamp, stage, status, page]);
}

function ArmBar() {
  useSetUp();
  const stamp = useStamp();
  const [person] = useSignerRows();
  const { armedAsset } = useStampState();
  const { signatures } = useSignatureState();
  const mark = person?.signatures[0];

  let hint = 'Getting ready…';
  if (signatures[0]) hint = `The field is signed by ${signatures[0].signer.name}`;
  else if (armedAsset) hint = 'Click the empty field to sign it, or anywhere else to place it';
  else if (mark) hint = 'Arm the signature, then click where it goes';

  return (
    <div className="toolbar">
      <button
        type="button"
        className="button"
        disabled={!mark}
        aria-pressed={armedAsset !== null}
        onClick={() => (armedAsset ? stamp.disarm() : mark && void stamp.armAsset(mark.id))}
      >
        {armedAsset ? 'Disarm' : 'Arm the signature'}
      </button>
      <output className="readout">{hint}</output>
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: ebook }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <ArmBar />
        <Stage className="stage">
          {() => (
            <>
              <RenderLayer />
              <AnnotationLayer />
              <FormLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}

Fill a field without signing#

Sometimes a signature only needs to look signed, such as for a form that gets printed. Draw the mark into the field without sealing anything:

await signature.fillField(toFieldRef('approval'), { source: pngBytes });
await signature.clearField(toFieldRef('approval'));

A signed field can’t be filled or cleared: what it shows is part of what was signed.

Loading live preview…

import { useEffect, useRef, useState } from 'react';
import { Viewer, DocumentGate, usePageList } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin, useStage } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { formPlugin, toFieldRef, useForm, useFormState } from '@embedpdf/react/form';
import { stampPlugin, useStamp } from '@embedpdf/react/stamp';
import { signaturePlugin, useSignature, useSignatureEvent } from '@embedpdf/react/signature';
import { localEngine } from '@embedpdf/engine';

import './fill.css';

const engine = localEngine();
const assetEngine = engine; // a person's marks are stamps, kept as PDFs; they open here too
// No key: a mark is only drawn in, nothing is sealed.
const plugins = [
  stagePlugin(),
  renderPlugin(),
  interactionPlugin(),
  formPlugin(),
  stampPlugin({ assetEngine }),
  signaturePlugin(),
];

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

const APPROVAL = toFieldRef('approval');

function FillBar() {
  const form = useForm();
  const stamp = useStamp();
  const stage = useStage();
  const signature = useSignature();
  const status = useFormState((state) => state.status);
  const page = usePageList().at(-1)?.ref;
  const [assetId, setAssetId] = useState<string | null>(null);
  const [drawn, setDrawn] = useState(false);
  const done = useRef(false);

  useSignatureEvent((plugin) => plugin.onFilled, () => setDrawn(true));
  useSignatureEvent((plugin) => plugin.onCleared, () => setDrawn(false));

  // On load: a signature field on the last page, a typed signature, drawn into the field.
  useEffect(() => {
    if (status !== 'ready' || !page || done.current) return;
    done.current = true;
    void (async () => {
      await form.create({
        family: 'signature',
        name: 'approval',
        widgets: [{ page, rect: { x: 72, y: 560, width: 220, height: 64 }, color: '#94a3b8' }],
      });
      stage.goToPage(page);
      const { library } = await stamp.createLibrary('Ada Lovelace', { kind: 'signatures' });
      const { asset } = await stamp.createAsset({
        libraryId: library.id,
        name: 'signature',
        label: 'Signature',
        mark: { kind: 'text', text: 'Ada Lovelace', fontFamily: 'times-italic', color: '#1d2b53' },
      });
      setAssetId(asset.id);
      await signature.fillField(APPROVAL, { assetId: asset.id });
    })();
  }, [form, stamp, stage, signature, status, page]);

  return (
    <div className="toolbar">
      <button
        type="button"
        className="button"
        disabled={!assetId || drawn}
        onClick={() => assetId && void signature.fillField(APPROVAL, { assetId })}
      >
        Draw it in
      </button>
      <button
        type="button"
        className="button"
        disabled={!drawn}
        onClick={() => void signature.clearField(APPROVAL)}
      >
        Take it out
      </button>
      <output className="readout">
        {drawn ? 'Drawn in, not signed: no key sealed anything' : 'The field is empty'}
      </output>
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: ebook }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <FillBar />
        <Stage className="stage">{() => <RenderLayer />}</Stage>
      </DocumentGate>
    </Viewer>
  );
}

The key#

The engine never holds a key. You give the plugin a signer, which does the signing. @embedpdf/react/signature has one for each case:

// Your own key and certificate chain
webCryptoSigner({ privateKey, certificateChain: [leaf, issuer] });
 
// Your signing service or hardware module: only the document's fingerprint leaves the browser
remoteSigner({ sign: ({ digest, algorithm, subFilter }) => api.sign(digest, algorithm, subFilter) });
 
// A key per person, created in the browser and kept there, never readable
personalSigner({ subject: 'Ada Lovelace', store: indexedDbKeyStore('my-app-keys') });
 
// For tests and demos
createTestSigner({ commonName: 'Demo' });

A personal signer works like signing in Preview, with real cryptography: a reader who trusts that person’s certificate sees a valid signature, and everyone else sees “validity unknown”, the honest answer for a key the person made themselves. For signatures everyone can check, sign with a certificate from a trusted provider, through webCryptoSigner or remoteSigner.

Signing in two steps#

When the key signs somewhere else, such as on a phone or in a signing service that asks for approval, split the signing in two:

const { signingId, digest } = await signature.prepareSignature({ field, mark: { assetId } });
const cms = await myService.sign(digest); // may take minutes
await signature.completeSignature(signingId, cms);

While a signature is prepared, the document can’t be changed, so nothing can slip in between. signature.cancelPending() gives up.

Check the signatures#

signature-list.tsx
import { useSignatureState } from '@embedpdf/react/signature';

export function SignatureList() {
  const { signatures } = useSignatureState();

  return (
    <ul>
      {signatures.map((sig) => (
        <li key={sig.fieldName}>
          {sig.fieldName}: {sig.verdict?.summary ?? 'checking…'}
        </li>
      ))}
    </ul>
  );
}

A verdict’s summary is:

SummaryMeans
'valid'Nothing changed since it was signed, and you trust the signer
'valid-untrusted'Nothing changed, but the signer’s certificate isn’t one you trust
'invalid'The document changed in a way the signature doesn’t allow
'indeterminate'It couldn’t be checked, for example because a certificate is missing

The plugin checks the signatures when the document opens, and again after every change. For a detailed report of what changed since a signature, rule by rule, use signature.analyzeChanges().

Warn before an edit breaks a signature#

After an approval signature, filling in the form and adding more signatures keep it valid, but an annotation doesn’t. The plugin warns you the moment a change would break a signature once it’s saved, as Acrobat does:

break-warning.tsx
import { useSignature, useSignatureEvent } from '@embedpdf/react/signature';
import { toast } from './toast';

export function SignatureGuard() {
  const signature = useSignature();

  useSignatureEvent(
    (s) => s.onInvalidationPredicted,
    ({ field }) => {
      const name = signature.getSignature(field)?.fieldName;
      toast(`This change will break the signature in "${name}" when saved.`);
    },
  );

  return null;
}

signature.getProtection() tells you what the document’s signatures allow, before anyone tries. A signer who wants comments to stay allowed signs with a certification that allows them.

Loading live preview…

import { useEffect, useRef, useState } from 'react';
import { Viewer, DocumentGate, usePageList } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin, useStage } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { AnnotationLayer, annotationPlugin, useAnnotation } from '@embedpdf/react/annotation';
import { formPlugin, toFieldRef, useForm, useFormState } from '@embedpdf/react/form';
import { stampPlugin, useStamp } from '@embedpdf/react/stamp';
import {
  createTestSigner,
  signaturePlugin,
  useSignature,
  useSignatureEvent,
  useSignatureState,
} from '@embedpdf/react/signature';
import { localEngine } from '@embedpdf/engine';

import './break-warning.css';

const engine = localEngine();
const assetEngine = engine; // a person's marks are stamps, kept as PDFs; they open here too
const signer = createTestSigner({ commonName: 'Ada Lovelace' });
const plugins = [
  stagePlugin(),
  renderPlugin(),
  interactionPlugin(),
  annotationPlugin(),
  formPlugin(),
  stampPlugin({ assetEngine }),
  signaturePlugin({
    key: () => signer,
    // Trust the demo key itself, so its signature checks out as 'valid'.
    trust: { anchors: async () => [(await signer).certificate] },
  }),
];

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

/** On load: a signature field on the last page, signed by Ada with a typed signature. */
function useSignedDocument() {
  const form = useForm();
  const stamp = useStamp();
  const stage = useStage();
  const signature = useSignature();
  const status = useFormState((state) => state.status);
  const page = usePageList().at(-1)?.ref;
  const done = useRef(false);

  useEffect(() => {
    if (status !== 'ready' || !page || done.current) return;
    done.current = true;
    void (async () => {
      await form.create({
        family: 'signature',
        name: 'approval',
        widgets: [{ page, rect: { x: 72, y: 560, width: 220, height: 64 } }],
      });
      stage.goToPage(page);
      const { library } = await stamp.createLibrary('Ada Lovelace', { kind: 'signatures' });
      const { asset } = await stamp.createAsset({
        libraryId: library.id,
        name: 'signature',
        label: 'Signature',
        mark: { kind: 'text', text: 'Ada Lovelace', fontFamily: 'times-italic', color: '#1d2b53' },
      });
      await signature.sign({ field: toFieldRef('approval'), mark: { assetId: asset.id } });
    })();
  }, [form, stamp, stage, signature, status, page]);
}

function WarningBar() {
  useSignedDocument();
  const annotation = useAnnotation();
  const signature = useSignature();
  const page = usePageList().at(-1)?.ref;
  const { signatures } = useSignatureState();
  const [warning, setWarning] = useState<string | null>(null);
  const signed = signatures[0];

  // The moment a change would break a signature once it's saved, as Acrobat warns.
  useSignatureEvent(
    (plugin) => plugin.onInvalidationPredicted,
    ({ field }) => {
      const name = signature.getSignature(field)?.fieldName;
      setWarning(`This change will break the signature in "${name}" when saved.`);
    },
  );

  return (
    <div className="toolbar">
      <button
        type="button"
        className="button"
        disabled={!signed || !page}
        onClick={() =>
          page &&
          void annotation.create(page, {
            subtype: 'square',
            box: { x: 320, y: 560, width: 140, height: 64 },
            color: '#e11d48',
            strokeWidth: 2,
          })
        }
      >
        Draw a box on the page
      </button>
      <output className="readout">
        {signed ? `Signed by ${signed.signer.name}: ${signed.verdict?.summary ?? 'checking…'}` : 'Signing…'}
      </output>
      {warning && <output className="warning">{warning}</output>}
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: ebook }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <WarningBar />
        <Stage className="stage">
          {() => (
            <>
              <RenderLayer />
              <AnnotationLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}

A person’s signatures#

A person’s signature and initials are stamps, in a library of kind 'signatures', drawn, typed or uploaded with the stamp plugin:

const { library } = await stamp.createLibrary('Ada Lovelace', { kind: 'signatures' });
await stamp.createAsset({ libraryId: library.id, name: 'signature', label: 'Signature', mark: { kind: 'ink', strokes } });
await stamp.createAsset({
  libraryId: library.id,
  name: 'initials',
  label: 'Initials',
  mark: { kind: 'text', text: 'AL', fontFamily: 'times-italic' },
});

useSignerRows() lists each person with their signature and initials, for a picker. The library is a normal PDF, so Acrobat can open it too.

”Sign here” in a form#

With the form layer, an empty signature field shows a “sign here” button. Clicking it makes the field the target: the next mark the person picks goes there. A signed field, clicked, asks your UI to show its details:

signature.setTarget(toFieldRef('approval')); // the next mark goes here; null clears
EventFires whenShow
onTargetChangedA field became the targetyour signatures panel
onSignRequestedIn 'ask' mode, a mark was dropped on a fieldyour sign dialog
onInspectionRequestedA signed field was clickedthe signature’s details

Methods#

Everything useSignature() gives you.

MethodWhat it does
sign({ field, mark })Signs a field: the mark becomes what it shows, and the key seals the document. Also takes signer, a per-call key, certify and lock, and resolves { signature, version, protection }. Sign a field
placeMark(mark, { field }), placeMark(mark, { page, center })Does what a click with an armed mark does: in a field, signs, fills or asks, by mode; anywhere else, places a stamp. Resolves what it did as kind: 'signed', 'filled', 'requested' or 'placed'. Let people click to sign
fillField(field, mark), clearField(field)Draws a mark into a field without signing, or takes it out again. Refused on a signed field. Fill a field without signing
prepareSignature({ field, mark }), completeSignature(signingId, cms)Signs in two steps: the first resolves { signingId, digest } for your key to sign, the second seals the document with what the key returned. Signing in two steps
cancelPending()Gives up a signature prepared in two steps, so the document can be changed again
validate({ until? })Checks every signature again and resolves the verdicts. until: 'persisted' checks the file as it was opened. Which bytes are checked
validateField(field)Checks one signed field and resolves its verdict
getVerdict(field), listVerdicts()One signed field’s verdict from the last check, or every verdict; null before the first check. Check the signatures
getSignature(field)One signature field’s facts, signed or not, such as fieldName, signed and signer, or null
listUnsignedFields()The signature fields still to sign, in document order
analyzeChanges({ since })What changed after a signature ({ signatureIndex }) or a version of the file ({ revisionIndex }), rule by rule
readRevision(field), readRevision({ revisionIndex })The exact bytes of the file version a signature covers. The signed bytes
setTarget(field)Makes a field the target, where the next mark the person picks goes; null clears. “Sign here” in a form
requestInspection(field)Asks your UI to show a signed field’s details, as clicking it does: onInspectionRequested fires
getMode()The mode in effect: the mode setting, or its default. Settings
getSnapshot()Everything at once, as the engine reads it: every signature field, signed or not, the file’s versions, and protection
refresh()Reads the signatures again. You rarely need it: the plugin reads and checks them again after every change.
canSign(field), canCertify(), canFill(field), canReadRevision()Whether signing a field, certifying, drawing a mark into a field without signing, and reading the signed bytes are allowed. Permissions
getSettings(), updateSettings(changes), resetSettings()Reads the settings, changes them while the app runs, or goes back to what you registered. In a component, use useSignatureSettings(). Settings

field is a field’s ref, such as toFieldRef('approval'); the methods that only read also take the ref of the field’s box. Every method that returns a promise also takes a signal in its options, to cancel it.

State#

Everything useSignatureState() gives you. Your component re-renders when a value changes. The method in the last column reads the same value once.

FieldWhat it isRead once
signaturesThe signed fields, in document order, each with its verdict once checkedlistSignatures()
protectionWhat the document’s signatures allow, or null before they’re readgetProtection()
targetThe field the next mark goes to, or nullgetTarget()
busyWhether a signing or a fill is runningisBusy()
pendingA signature prepared in two steps and not completed yet, as { signingId, field }, or null. Until it’s completed or cancelled, the document can’t be changed.getPending()
statusWhether the signatures are read: 'idle', 'loading', 'ready', 'forbidden' or 'error'getStatus()

Settings#

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

SettingWhat it doesDefault
keyThe signer, or a function that returns one when someone signsnone
modeWhat a mark does in a field: 'sign', 'visual' or 'ask''sign' with a key, else 'visual'
trustThe certificates you trust, for checking signaturesnone
allowCertifyLet a first signature be a certification, which sets what stays allowedfalse

Events#

save-warning.tsx
import { useSignatureEvent } from '@embedpdf/react/signature';
import { showWarning } from './warnings';

export function SaveWarning() {
  useSignatureEvent(
    (signature) => signature.onInvalidationPredicted,
    () => showWarning('Saving this change will break a signature.'),
  );

  return null;
}
EventFires whenCarries
onSignedA field was signed, whoever signed itfield, result, origin
onFilled, onClearedA mark was drawn into a field, or removedfield
onValidatedThe signatures were checkedverdicts
onProtectionChangedWhat the signatures allow changedprotection
onInvalidationPredictedA change would break a signature once savedfield, detail
onTargetChangedA field became the target, or the target was clearedfield (null when cleared)
onSignRequestedIn 'ask' mode, a mark was dropped on a fieldfield, mark
onInspectionRequestedA signed field was clickedfield
onSettingsChangedThe settings changedsettings, changed

result is what sign() resolves. “Sign here” in a form says what to show for the last three.

Permissions#

PermissionWhat it allowsCheck
doc.signSigningsignature.canSign(field)
doc.sign.certifySigning a certificationsignature.canCertify()
doc.forms.fillDrawing a mark into a field without signingsignature.canFill(field)
doc.downloadReading the exact bytes a signature coverssignature.canReadRevision()

A user with a fields:sign (fields:fill) permission for one group signs (fills in) that group’s fields only, so the checks take the field. See Signers and groups. On a signed document, the engine also refuses what its signatures forbid.

Good to know#

Which bytes are checked#

The plugin checks the document as it is in the viewer, with changes that haven’t been downloaded yet, so the verdict is the one the downloaded file will get. validate({ until: 'persisted' }) checks the file as it was opened.

The signed bytes#

signature.readRevision({ revisionIndex }) gives you the exact version of the file a signature covers, for an audit trail.

How signatures are stored, and what each certification allows, is on Digital signatures.

Was this page helpful?

Your feedback goes directly to the documentation team.