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 withSignature() next to withForm() and withStamp(), with the key to sign with:

Loading live preview…

import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  input,
  output,
  signal,
  untracked,
  viewChild,
  ViewEncapsulation,
} from '@angular/core';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfForm, EpdfFormLayer, toFieldRef, withForm } from '@embedpdf/angular/form';
import { EpdfStamp, withStamp } from '@embedpdf/angular/stamp';
import { createTestSigner, EpdfSignature, withSignature } from '@embedpdf/angular/signature';
import { localEngine } from '@embedpdf/engine';

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 agreement = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/agreement.pdf');
  return { kind: 'bytes', id: 'agreement', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// A mark's button: its picture once there is one, its label until then.
@Component({
  selector: 'button[demoMarkButton]',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { type: 'button', class: 'button', '[title]': 'label()', '(click)': 'pick.emit()' },
  template: `
    @if (url(); as url) {
      <img [src]="url" [alt]="label()" class="preview" />
    } @else {
      {{ label() }}
    }
  `,
})
export class MarkButton {
  readonly assetId = input.required<string>();
  readonly label = input.required<string>();
  readonly pick = output();
  protected readonly url = inject(EpdfStamp).previewUrlOf(() => this.assetId());
}

@Component({
  selector: 'demo-root',
  imports: [
    EpdfDocumentGate,
    EpdfStage,
    EpdfPageTemplate,
    EpdfRenderLayer,
    EpdfFormLayer,
    MarkButton,
  ],
  providers: [
    provideEmbedPdf(
      { engine, initialDocuments: [{ source: agreement }] },
      withStage(),
      withRender(),
      withInteraction(),
      withForm(),
      withStamp({ assetEngine }),
      withSignature({
        signingKey: () => signer,
        // Trust the demo key itself, so its signatures check out as 'valid'.
        trust: { anchors: async () => [(await signer).certificate] },
      }),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './basic.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="toolbar">
        @for (asset of person()?.signatures; track asset.id) {
          <button
            demoMarkButton
            [assetId]="asset.id"
            [label]="asset.label"
            (pick)="sign(asset.id)"
          ></button>
        }
        <output class="readout">{{ status() }}</output>
      </div>
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <!-- An empty signature field is "sign here": a click makes it the target -->
          <epdf-form-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  private readonly form = inject(EpdfForm);
  private readonly stamp = inject(EpdfStamp);
  private readonly signature = inject(EpdfSignature);
  private readonly stage = viewChild(EpdfStage);
  private done = false;

  protected readonly person = computed(() => this.signature.signerRows()[0]);
  private readonly field = computed(() =>
    this.form.fields().find((candidate) => candidate.kind === 'signature'),
  );
  private readonly error = signal<string | null>(null);

  protected readonly status = computed(() => {
    // Ada's signature, once she signs: the agreement already carries Lanternfield's.
    const signed = this.signature.signatures().find((each) => each.fieldName === 'approval');
    const error = this.error();
    if (!this.person() || !this.field()) return 'Getting ready…';
    if (error) return error;
    if (this.signature.busy()) return 'Signing…';
    if (signed) return `Signed by ${signed.signer.name}: ${signed.verdict?.summary ?? 'checking…'}`;
    if (this.signature.target()) return 'Now pick the signature';
    return 'Click the field, or pick the signature';
  });

  constructor() {
    // Start at the agreement's signature field. The browser holds no signatures
    // yet: add one person with a typed signature.
    effect(() => {
      const stage = this.stage();
      if (this.form.status() !== 'ready' || !stage || this.done) return;
      this.done = true;
      untracked(() => void this.setUp(stage));
    });
  }

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

  private async setUp(stage: EpdfStage) {
    // Bring the agreement's signature field into view.
    const first = this.form.get(toFieldRef('approval'))?.widgets[0];
    const widget = first ? this.form.getWidget(first) : null;
    if (widget) stage.reveal(widget.page, { rect: widget.rect });
    const { library } = await this.stamp.createLibrary('Ada Lovelace', { kind: 'signatures' });
    await this.stamp.createAsset({
      libraryId: library.id,
      name: 'signature',
      label: 'Signature',
      mark: { kind: 'text', text: 'Ada Lovelace', fontFamily: 'times-italic', color: '#1d2b53' },
    });
  }
}
signature-plugin.ts
import { Component } from '@angular/core';
import { withForm } from '@embedpdf/angular/form';
import { provideEmbedPdf } from '@embedpdf/angular/runtime';
import { indexedDbKeyStore, personalSigner, withSignature } from '@embedpdf/angular/signature';
import { withStamp } from '@embedpdf/angular/stamp';
import { rootCertificate } from './certificates';
import { engine } from './pdf';

@Component({
  selector: 'app-signing',
  providers: [
    provideEmbedPdf(
      { engine },
      /* … */
      withForm(),
      withStamp(),
      withSignature({
        signingKey: () =>
          personalSigner({ subject: 'Ada Lovelace', store: indexedDbKeyStore('my-app-keys') }),
        trust: { anchors: async () => [rootCertificate] }, // the certificates you trust
      }),
    ),
  ],
  template: `<!-- … -->`,
})
export class Signing {}

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

Leave mark out, and the field keeps what it shows: a mark that was drawn into it earlier, or nothing. A field signed with nothing in it holds a signature that shows nowhere on the page.

A signature seals what the person sees. Text typed into a form field’s box that the cursor hasn’t left is written first, as leaving the box would, so it’s part of what is signed. When the form’s own rules refuse that text, sign() rejects invalid-input and signs nothing; error.details.fields names the fields. It rejects the same way again, also when the box was left before the call, until the person has dealt with that text: typed something else, pressed Escape in the box, or gone back to a box that shows the field’s value again and left it. Typed text that couldn’t be written, such as on a dropped connection, stays typed: sign() rejects as setValue() does, and the next call writes it again.

A signing you cancel, with sign(input, { signal }), writes nothing from then on. Cancelled while the key is asked for, it rejects operation-cancelled at once: the typed text stays typed, and the key signs nothing.

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 an image field the person fills in, such as their initials, the mark goes in as its picture, in place of any picture it holds;
  • over a signed field, or a signature or image field that isn’t theirs, nothing happens and the mark stays armed;
  • anywhere else, the mark is placed as a stamp, even over a button that does something or one that only shows a picture, such as a logo.

A mark that goes into a field is disarmed, and the tool goes back to the one people had before they armed it, so the fields take input again. A mark placed as a stamp stays armed for the next. With annotationCommands and the command shortcuts, Escape puts an armed mark away the same way.

The mark’s preview shows what a click does. Over a field it goes into, it sits in the field as the field will draw it: fitted whole and centred, inside the border of an image field, turned with a turned field, above the field’s tint. The field’s placeholder, such as “Signature”, stands down while the preview is in it. Over a field that isn’t theirs there’s no preview, and the pointer says no (not-allowed). Anywhere else it follows the pointer, as a stamp’s does.

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, 'finish' draws it in until the signer finishes, and 'ask' asks your UI first through signRequested$, so you can show your own sign dialog.

An image field, such as the person’s initials, is no signature: in every mode placeMark() puts the mark in as its picture, through form.setButtonImage(). It’s filling in, so it takes the right to fill the field in, never signs or asks, and is one step to undo. It resolves 'filled' and fires filled$, as fillField() does. No other push button takes a mark: placeMark() rejects invalid-input for one, a button that only shows a picture among them.

Loading live preview…

import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  untracked,
  viewChild,
  ViewEncapsulation,
} from '@angular/core';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfAnnotationLayer, withAnnotation } from '@embedpdf/angular/annotation';
import { EpdfForm, EpdfFormLayer, toFieldRef, withForm } from '@embedpdf/angular/form';
import { EpdfStamp, withStamp } from '@embedpdf/angular/stamp';
import { createTestSigner, EpdfSignature, withSignature } from '@embedpdf/angular/signature';
import { localEngine } from '@embedpdf/engine';

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 agreement = async (): Promise<OpenInput> => {
  const response = await fetch('https://www.embedpdf.com/pdfs/agreement.pdf');
  return { kind: 'bytes', id: 'agreement', bytes: new Uint8Array(await response.arrayBuffer()) };
};

@Component({
  selector: 'demo-root',
  imports: [
    EpdfDocumentGate,
    EpdfStage,
    EpdfPageTemplate,
    EpdfRenderLayer,
    EpdfAnnotationLayer,
    EpdfFormLayer,
  ],
  providers: [
    provideEmbedPdf(
      { engine, initialDocuments: [{ source: agreement }] },
      withStage(),
      withRender(),
      withInteraction(),
      withAnnotation(),
      withForm(),
      withStamp({ assetEngine }),
      withSignature({ signingKey: () => signer }),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './click-to-sign.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="toolbar">
        <button
          type="button"
          class="button"
          [disabled]="!mark()"
          [attr.aria-pressed]="stamp.armedAsset() !== null"
          (click)="toggleArmed()"
        >
          {{ stamp.armedAsset() ? 'Disarm' : 'Arm the signature' }}
        </button>
        <output class="readout">{{ hint() }}</output>
      </div>
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-annotation-layer />
          <epdf-form-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  protected readonly stamp = inject(EpdfStamp);
  private readonly form = inject(EpdfForm);
  private readonly signature = inject(EpdfSignature);
  private readonly stage = viewChild(EpdfStage);
  private done = false;

  protected readonly mark = computed(() => this.signature.signerRows()[0]?.signatures[0]);

  protected readonly hint = computed(() => {
    // Ada's signature, once she signs: the agreement already carries Lanternfield's.
    const signed = this.signature.signatures().find((each) => each.fieldName === 'approval');
    if (signed) return `The field is signed by ${signed.signer.name}`;
    if (this.stamp.armedAsset())
      return 'Click the empty field to sign it, or anywhere else to place it';
    if (this.mark()) return 'Arm the signature, then click where it goes';
    return 'Getting ready…';
  });

  constructor() {
    // On load: the agreement, where the form's signature field is, and a person's signature, armed.
    effect(() => {
      const stage = this.stage();
      if (this.form.status() !== 'ready' || !stage || this.done) return;
      this.done = true;
      untracked(() => void this.setUp(stage));
    });
  }

  protected toggleArmed() {
    const mark = this.mark();
    if (this.stamp.armedAsset()) this.stamp.disarm();
    else if (mark) void this.stamp.armAsset(mark.id);
  }

  private async setUp(stage: EpdfStage) {
    // Bring the agreement's signature field into view.
    const first = this.form.get(toFieldRef('approval'))?.widgets[0];
    const widget = first ? this.form.getWidget(first) : null;
    if (widget) stage.reveal(widget.page, { rect: widget.rect });
    const { library } = await this.stamp.createLibrary('Ada Lovelace', { kind: 'signatures' });
    const { asset } = await this.stamp.createAsset({
      libraryId: library.id,
      name: 'signature',
      label: 'Signature',
      mark: { kind: 'text', text: 'Ada Lovelace', fontFamily: 'times-italic', color: '#1d2b53' },
    });
    await this.stamp.armAsset(asset.id, { targetWidth: 160 });
  }
}

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.

Each is one change, so with the history plugin it is one step to undo: an undo takes a placed mark out again, and brings back a mark that was cleared or replaced. An undo or a redo fires neither filled$ nor cleared$: a field’s box says what it holds, as hasMark.

A field with a mark drawn in it counts as filled in, signed or not: a required one leaves the list of what’s still to fill in, and clearField() puts it back. So in 'visual' mode a form with required signature fields can be completed.

Loading live preview…

import {
  ChangeDetectionStrategy,
  Component,
  effect,
  inject,
  signal,
  untracked,
  viewChild,
  ViewEncapsulation,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfForm, toFieldRef, withForm } from '@embedpdf/angular/form';
import { EpdfStamp, withStamp } from '@embedpdf/angular/stamp';
import { EpdfSignature, withSignature } from '@embedpdf/angular/signature';
import { localEngine } from '@embedpdf/engine';

const engine = localEngine();
const assetEngine = engine; // a person's marks are stamps, kept as PDFs; they open here too

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

const APPROVAL = toFieldRef('approval');

@Component({
  selector: 'demo-root',
  imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer],
  providers: [
    provideEmbedPdf(
      { engine, initialDocuments: [{ source: agreement }] },
      withStage(),
      withRender(),
      withInteraction(),
      withForm(),
      withStamp({ assetEngine }),
      // No key: a mark is only drawn in, nothing is sealed.
      withSignature(),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './fill.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="toolbar">
        <button type="button" class="button" [disabled]="!assetId() || drawn()" (click)="drawIn()">
          Draw it in
        </button>
        <button type="button" class="button" [disabled]="!drawn()" (click)="takeOut()">
          Take it out
        </button>
        <output class="readout">
          {{ drawn() ? 'Drawn in, not signed: no key sealed anything' : 'The field is empty' }}
        </output>
      </div>
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  private readonly form = inject(EpdfForm);
  private readonly stamp = inject(EpdfStamp);
  private readonly signature = inject(EpdfSignature);
  private readonly stage = viewChild(EpdfStage);
  private done = false;
  protected readonly assetId = signal<string | null>(null);
  protected readonly drawn = signal(false);

  constructor() {
    this.signature.filled$.pipe(takeUntilDestroyed()).subscribe(() => this.drawn.set(true));
    this.signature.cleared$.pipe(takeUntilDestroyed()).subscribe(() => this.drawn.set(false));

    // On load: Ada's typed signature, ready to draw in, and the signature field in view.
    effect(() => {
      const stage = this.stage();
      if (this.form.status() !== 'ready' || !stage || this.done) return;
      this.done = true;
      untracked(() => void this.setUp(stage));
    });
  }

  protected drawIn() {
    const assetId = this.assetId();
    if (assetId) void this.signature.fillField(APPROVAL, { assetId });
  }

  protected takeOut() {
    void this.signature.clearField(APPROVAL);
  }

  private async setUp(stage: EpdfStage) {
    // Bring the agreement's signature field into view.
    const first = this.form.get(APPROVAL)?.widgets[0];
    const widget = first ? this.form.getWidget(first) : null;
    if (widget) stage.reveal(widget.page, { rect: widget.rect });
    const { library } = await this.stamp.createLibrary('Ada Lovelace', { kind: 'signatures' });
    const { asset } = await this.stamp.createAsset({
      libraryId: library.id,
      name: 'signature',
      label: 'Signature',
      mark: { kind: 'text', text: 'Ada Lovelace', fontFamily: 'times-italic', color: '#1d2b53' },
    });
    this.assetId.set(asset.id);
  }
}

Sign as the last step#

When a signer also fills in a form, their signature comes last. It seals what they filled in, and a signature made first would lock their fields before they’re filled in. Set mode: 'finish':

withSignature({ signingKey, mode: 'finish' });

Now a mark placed in a signature field is only drawn in: placeMark() resolves 'filled', as in 'visual' mode. The signer can replace it, take it out with clearField(), and fill in the other fields in any order. One call seals their part:

const result = await signature.finish();
 
if (result.status === 'incomplete') {
  result.missing; // the required fields that are still empty
  result.invalid; // values a rule refuses: [{ field, message }]
} else {
  result.field; // the field it signed
  result.result; // everything sign() resolves
}

finish() goes through these steps, in this order:

  1. Picks the field: the signature field the user may sign and hasn’t signed. With several, it’s the first in document order; finish({ field }) names another.
  2. Writes the day of signing into the user’s own date-signed fields, in each field’s date pattern, as one change. It comes before the checks: a rule of the form may read it.
  3. Writes what’s still being typed. Text typed into a box the cursor hasn’t left is written, as leaving the box would, so it’s part of what is checked and signed.
  4. Checks the user’s fields as form.validateValues() does, and that the signature field holds a mark. When something is missing or invalid, it signs nothing and resolves { status: 'incomplete', missing, invalid }.
  5. Asks for the key. A signingKey function is called now, so a signer hears what’s missing before they’re asked for a PIN.
  6. Has the engine prepare the signing, after writing what was typed meanwhile, and the date once more when the day turned. From here until the signing is done the engine takes no change, from anyone.
  7. Checks the form the engine prepared. It’s the check of step 4, of the form as the engine holds it: the form may have changed since step 4. A form that’s no longer complete resolves incomplete too: the prepared signing is cancelled, and the key signs nothing.
  8. Signs the field with the key, keeping the mark that’s in it.
  9. Adds the validation data and the document timestamp, as sign() does.

Then it resolves { status: 'signed', field, result }.

  • An empty signature field is missing, required or not: the signer places their mark first.
  • It writes no other value. A signer’s name and email address are form.prefill()‘s, when they start. A value they changed stays, and a field they emptied stays empty.
  • The day of signing is inside what was signed. prefill() wrote the day the signer started; finish() writes the day they sign, so a signer who comes back later signs today’s date.
  • Their part is final after it. The signature locks what the signer signed:
    • A field in a group locks its group, as sign() does.
    • A field in no group locks every field in no group that holds a value: text that isn’t empty, a ticked checkbox, a chosen radio button, a selected option, an image field’s picture. The day of signing is among them. Empty fields and the other signature fields stay open, so the next person fills in theirs and signs. They are the fields of the form that is signed: one filled in while finish() ran is locked with the rest.
    • A signature field with a lock of its own in the PDF keeps that one.
    • lock says it yourself, as for sign(). lock: null adds no lock of finish()‘s own: the signing locks what sign() locks by itself.
  • signer, certify, signingKey and timestampAuthority are passed as for sign(): finish({ signer: { reason } }).
  • It needs a key, the signingKey setting or one with the call, and works in every mode.
  • canFinish() says whether there’s a field for this user to sign. Show your Finish button by it: it’s false once they finished.
  • Ask for consent before you call it. What the signer agrees to is your app’s own text.

A signing can’t be undone, and it empties the history: the mark, the values and the date before it are no longer steps to undo.

What is sealed is what the last check saw. That check is made once the engine has stopped taking changes, and of the form the engine holds, with the date in it. Both checks are made with today’s date written, so a date that a rule compares with the day of signing is checked against the day that is signed, not the day the signer started.

  • A change made while it runs is checked, or refused. One made before the signing is prepared, such as while the signer is asked for a PIN, is part of the last check: a value that passes is signed, and one that leaves the form incomplete resolves incomplete. One made after it rejects conflict and is no part of what is signed.
  • An incomplete form has today’s date written in its date-signed fields. The key isn’t asked for when the first check finds it incomplete.
  • Typed text the form refuses is invalid. When the form’s own rules refuse what was typed, the field keeps the value it had, and finish() lists it in invalid with no message: the signer meant another value. The refusal itself is reported as any is, through validationRejected$.
    • It stays invalid until the signer deals with it. finish() resolves incomplete again, also when the box was left before Finish was pressed, until they type something else or press Escape in the box, or the field takes another value, such as a date picked from a calendar.
    • Put the cursor back in that field, with the form’s focus(field.ref), and say that the change wasn’t taken. A box that shows the field’s value again gives the edit up when the signer leaves it. One that still shows the refused text asks the form again.
  • Typed text that couldn’t be written is written again. When its write fails, such as on a dropped connection, finish() rejects as setValue() does and the text stays in its box. The next finish() writes it, so what is signed is still what the box shows.
  • Keep the form still while it runs. busy() is true from the first step to the seal, also while another signature call ends meanwhile, so disable your form by it. Once the signing is prepared, the engine refuses every change until it’s done.

When finish() rejects#

An incomplete form is an answer, never a rejection. finish() rejects when it can’t start, and then nothing is checked or written:

RejectsWhen
not-foundThere’s no signature field for this user to sign: someone who only fills in, or a second finish(). Also for a field that is no signature field
permission-deniedThe field isn’t theirs to sign, or certify without doc.sign.certify
conflictThe field is signed, another finish() is running, or a signature prepared in two steps is pending
invalid-inputThere’s no key

It also rejects when a step fails on the way:

  • The check can’t run. validateValues() rejects operation-failed when a field’s script doesn’t run to its end. finish() rejects the same way, and signs nothing.
  • The key isn’t handed over. A signingKey function that rejects, such as when the signer closes your PIN dialog, makes finish() reject with its error. Nothing is prepared or signed; the day of signing is written by then and stays.
  • The key refuses to sign, or the timestamp authority fails. It rejects as sign() does. The day of signing is written by then and stays: nothing is signed, no field is locked, no signing is left pending, and finish() can be called again.
  • The form keeps changing. For a field in no group, the lock names the fields that hold a value, and it’s part of what the engine prepares. When a field is filled in or emptied right as the signing is prepared, finish() prepares it again with the lock of the form as it is. After three tries it rejects conflict, with nothing signed.

A signing flow builds a flow for several signers on it.

The key#

The engine never holds a key. You give the plugin a signer, which does the signing. @embedpdf/angular/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. Text someone is still typing is written before the signature is prepared, as for sign().

completeSignature() checks what the key returned before it seals anything. When it fails, nothing is written and the signature stays prepared:

  • The timestamp authority didn’t answer (Network): call completeSignature() again with the same cms. The key doesn’t sign twice.
  • The cms was refused (SignatureRefused), for example because it signs another fingerprint: it will be refused again. Call cancelPending() and start over.

A timestamp with every signature#

A signature says when it was made, by the signer’s own clock. A timestamp authority vouches for that time, so a reader doesn’t have to take the signer’s word for it, and the signature can still be checked after the signer’s certificate expires. Set one when you register the plugin, and every signature it seals carries a timestamp:

withSignature({
  signingKey,
  timestampAuthority: httpTimestampAuthority({
    url: '/api/timestamp',
  }),
});

httpTimestampAuthority() comes from the same place as the signers. Most authorities can’t be called from a web page, so url is a route of your own that passes the request on; Reach the authority from a browser has one.

  • A timestamp is never skipped. When the authority can’t be reached or its answer doesn’t check out, the signing fails and nothing is signed.
  • One signature without a timestamp: pass timestampAuthority: null to that sign() or prepareSignature(). Pass another authority to use that one instead.
  • In two steps, prepareSignature() reserves room for the timestamp and completeSignature() adds it.
  • With trust set, the authority must be one you trust. The plugin won’t seal a timestamp from an authority your trust doesn’t cover, so a wrong address fails at the first signature and not at the first reader. List the authority’s root under timestampAnchors:
withSignature({
  signingKey,
  timestampAuthority,
  trust: {
    anchors: async () => [companyRoot],
    timestampAnchors: async () => [authorityRoot],
  },
});

Keep a signature checkable for years#

A timestamp proves when a signature was made. To check the signature years later, a reader also has to know that the signer’s certificate had not been withdrawn by then, and its issuer may no longer answer that question. Set revocation, and every signature the plugin seals gets those answers right after, stored in the file. Acrobat shows such a signature as “LTV enabled”:

withSignature({
  signingKey,
  timestampAuthority: httpTimestampAuthority({ url: '/api/timestamp' }),
  revocation: httpRevocationSource({ url: '/api/revocation' }),
  documentTimestamp: true,
  trust,
});

httpRevocationSource() comes from the same place as the signers. A web page can’t call a certificate’s issuer, so url is a route of your own that passes the question on; Reach the issuers from a browser has one.

  • It needs trust and a timestamp. The answers kept are the ones for the certificates between the signer and a certificate you trust, at the time the timestamp proves.
  • documentTimestamp: true adds a document timestamp after the answers, from timestampAuthority. It proves the answers were in the file by then, which a strict validator asks for.
  • The signature is sealed first. The answers go into the file after the signature, so a failure there can’t undo it: sign() still resolves, and its result says what happened.
const result = await signature.sign({ field, mark });
 
result.validationInfo;
// { added: { certificates: 3, ocspResponses: 2, crls: 0 },
//   documentTimestamp: { kind: 'fqn', name: 'Timestamp1' } }
 
if (result.validationInfoError) {
  // Signed, but the file doesn't hold the answers yet. Try again later:
  await signature.addValidationInfo(result.signature.field);
}
  • Only the signature just made is covered. Other people’s signatures may name issuers that no longer answer. signature.addValidationInfo() with no field covers every signature, and rejects when one can’t be covered.
  • It takes the doc.sign permission. Someone who may only sign their own group’s fields signs without it, and result.validationInfo is null. Whoever finishes the document then calls signature.addValidationInfo() once, for everyone.
  • completeSignature() and placeMark() do the same as sign().

Check the signatures#

signature-list.ts
import { Component, inject } from '@angular/core';
import { EpdfSignature } from '@embedpdf/angular/signature';

@Component({
  selector: 'app-signature-list',
  template: `
    <ul>
      @for (sig of signature.signatures(); track sig.fieldName) {
        <li>{{ sig.fieldName }}: {{ sig.verdict?.summary ?? 'checking…' }}</li>
      }
    </ul>
  `,
})
export class SignatureList {
  protected readonly signature = inject(EpdfSignature);
}

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

'valid' means the signer’s certificate is within its dates and leads to one you trust. Whether it was withdrawn is in verdict.revocation: 'good', 'revoked' or 'unknown', read from the answers the file holds. Proof of a withdrawal makes the summary 'invalid', and 'unknown' never changes it. The plugin asks nobody when it checks, so opening a document doesn’t tell a certificate authority who is reading it.

Whether it can be checked for years#

verdict.longTerm says whether the file holds everything a reader needs, with no network:

const { longTerm } = verdict;
 
longTerm.enabled; // true: what Acrobat calls "LTV enabled"
longTerm.expiresAt; // the day that proof runs out, or null
longTerm.missing; // what stands in the way: [{ certificate, reason }]

For a signature that isn’t there yet, offer to add what is missing:

if (!verdict.longTerm.enabled && signature.canAddValidationInfo()) {
  await signature.addValidationInfo(verdict.signature.field);
}

addValidationInfo() asks through the revocation setting, stores the answers, and adds a document timestamp when documentTimestamp is set and the answers aren’t covered by one yet. It rejects, and stores nothing, when an answer is missing: error.details.reason says why ('no-timestamp', 'untrusted', 'no-answer' or 'revoked'), and error.details.source names an address that didn’t answer. Long-term validation has every field.

When it was signed#

A signature with a timestamp has a second verdict, in verdict.timestamp: null when the signature has none. Show the time the authority vouches for when you trust it, and the signer’s own claim otherwise:

const stamp = verdict.timestamp;
const when =
  stamp?.summary === 'valid'
    ? `${stamp.stampedAt}, confirmed by ${stamp.authorityName}`
    : `${verdict.signature.signer.signedAt}, the signer's clock`;

A timestamp’s verdict never changes the signature’s summary: a valid signature with a broken timestamp is still valid.

Each certificate is judged at the signature’s trusted timestamp, when it has one, so a signature whose signer’s certificate has expired since still reads 'valid'. To judge every certificate as of now:

await signature.validate({
  validationTime: { kind: 'now' },
});

The timestamp has every field of the verdict, and what this option does and doesn’t check.

Warn before an edit breaks a signature#

After an approval signature, filling in the form, commenting and adding more signatures keep it valid, as in Acrobat. Other changes break it once the file is saved, such as adding a form field. The plugin warns you the moment a change would do that, as Acrobat does:

break-warning.ts
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { EpdfSignature } from '@embedpdf/angular/signature';
import { toast } from './toast';

@Component({ selector: 'app-signature-guard', template: '' })
export class SignatureGuard {
  private readonly signature = inject(EpdfSignature);

  constructor() {
    this.signature.invalidationPredicted$.pipe(takeUntilDestroyed()).subscribe(({ field }) => {
      const name = this.signature.getSignature(field)?.fieldName;
      toast(`This change will break the signature in "${name}" when saved.`);
    });
  }
}

signature.getProtection() tells you what the document’s signatures allow, before anyone tries. A signer who wants to rule out more, such as comments, certifies the document to allow form filling only: the engine then refuses those changes instead of warning about them.

Loading live preview…

import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  signal,
  untracked,
  viewChild,
  ViewEncapsulation,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfAnnotation, EpdfAnnotationLayer, withAnnotation } from '@embedpdf/angular/annotation';
import { EpdfForm, toFieldRef, withForm } from '@embedpdf/angular/form';
import { EpdfSignature, withSignature } from '@embedpdf/angular/signature';
import { localEngine } from '@embedpdf/engine';

const engine = localEngine();

// The certificate Lanternfield signed the agreement with, published next to it. Trusting it is what
// makes the signature read 'valid'; your app trusts its own certificates the same way.
const lanternfieldCertificate = async () => {
  const response = await fetch('https://www.embedpdf.com/pdfs/agreement.cer');
  return new Uint8Array(await response.arrayBuffer());
};

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

// Lanternfield's signature field, signed before the agreement was sent.
const PROVIDER = toFieldRef('provider');

// Two edits after an approval signature: a comment keeps it valid, a new form field breaks it.
@Component({
  selector: 'demo-root',
  imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfAnnotationLayer],
  providers: [
    provideEmbedPdf(
      { engine, initialDocuments: [{ source: agreement }] },
      withStage(),
      withRender(),
      withInteraction(),
      withAnnotation(),
      withForm(),
      withSignature({ trust: { anchors: async () => [await lanternfieldCertificate()] } }),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './break-warning.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="toolbar">
        <button
          type="button"
          class="button"
          [disabled]="!signed() || made().comment"
          (click)="addComment()"
        >
          Add a comment
        </button>
        <button
          type="button"
          class="button"
          [disabled]="!signed() || made().field"
          (click)="addField()"
        >
          Add a form field
        </button>
        <output class="readout">{{ status() }}</output>
        @if (warning(); as warning) {
          <output class="warning">{{ warning }}</output>
        }
      </div>
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-annotation-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  private readonly form = inject(EpdfForm);
  private readonly annotation = inject(EpdfAnnotation);
  private readonly signature = inject(EpdfSignature);
  private readonly stage = viewChild(EpdfStage);
  private revealed = false;

  protected readonly signed = computed(() =>
    this.signature.signatures().find((each) => each.signed),
  );
  protected readonly status = computed(() => {
    const signed = this.signed();
    return signed
      ? `Signed by ${signed.signer.name}: ${signed.verdict?.summary ?? 'checking…'}`
      : 'Opening…';
  });
  protected readonly warning = signal<string | null>(null);
  protected readonly made = signal({ comment: false, field: false });

  /** Where the signature is: the edits go next to it. */
  private readonly widget = computed(() => {
    const first = this.form.get(PROVIDER)?.widgets[0];
    return first ? this.form.getWidget(first) : null;
  });

  constructor() {
    // The moment a change would break a signature once it's saved, as Acrobat warns.
    this.signature.invalidationPredicted$.pipe(takeUntilDestroyed()).subscribe(({ field }) => {
      const name = this.signature.getSignature(field)?.fieldName;
      this.warning.set(`This change will break the signature in "${name}" when saved.`);
    });

    // On load: the signatures, in view. Nothing is changed until a button is pressed.
    effect(() => {
      const stage = this.stage();
      if (this.form.status() !== 'ready' || !stage || this.revealed) return;
      this.revealed = true;
      untracked(() => {
        const widget = this.widget();
        if (widget) stage.reveal(widget.page, { rect: widget.rect });
      });
    });
  }

  protected async addComment() {
    const widget = this.widget();
    if (!widget) return;
    const { rect } = widget;
    await this.annotation.create(widget.page, {
      subtype: 'text',
      rect: { x: rect.x + rect.width + 6, y: rect.y, width: 20, height: 20 },
      contents: 'Looks good to us.',
    });
    this.made.update((current) => ({ ...current, comment: true }));
  }

  protected async addField() {
    const widget = this.widget();
    if (!widget) return;
    const { rect } = widget;
    await this.form.create({
      kind: 'text',
      name: 'purchase_order',
      widgets: [
        {
          page: widget.page,
          rect: { x: rect.x, y: rect.y + rect.height + 36, width: rect.width, height: 24 },
        },
      ],
    });
    this.made.update((current) => ({ ...current, field: true }));
  }
}

Try it: Lanternfield signed this agreement before sending it. Add a comment: the signature stays valid. Add a form field: the warning shows before anything is saved.

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

signature.signerRows() 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 can be clicked. The layer draws no “sign here” text in it: the field is a button with nothing in it, named after the field for screen readers. 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. An image field is a target too, empty or filled: clicking it lets the person put their mark in, or a new one over it:

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

Methods#

Everything inject(EpdfSignature) gives you.

MethodWhat it does
sign({ field, mark })Signs a field: the mark becomes what it shows, and the key seals the document. Without mark, the field keeps what it shows. Also takes signer, a per-call signingKey and timestampAuthority, certify and lock, and resolves { signature, version, protection, validationInfo, validationInfoError }. 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 ('visual' and 'finish' fill); in an image field, always puts the mark in as its picture; 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, each as one step to undo. Refused on a signed field. Fill a field without signing
finish(options?)Seals the user’s part as the last step: picks their signature field, writes the day of signing, checks their fields, signs with the mark that’s in the field, and adds the validation data. Resolves { status: 'signed', field, result } or { status: 'incomplete', missing, invalid }. Sign as the last step
prepareSignature({ field, mark }), completeSignature(signingId, cms)Signs in two steps: the first resolves { signingId, digest } for your key to sign, the second checks what the key returned, adds the timestamp when an authority is set, and seals the document. Signing in two steps
cancelPending()Gives up a signature prepared in two steps, so the document can be changed again
validate({ until?, validationTime? })Checks every signature again and resolves the verdicts. until: 'persisted' checks the file as it was opened; validationTime judges each signature at its timestamp. Which bytes are checked, When it was signed
validateField(field)Checks one signed field and resolves its verdict
addValidationInfo(field?)Asks whether a signed field’s certificates were good at its timestamp, stores the answers in the file, and adds a document timestamp when documentTimestamp is set. Without field, for every signature. Resolves { added, documentTimestamp }. Whether it can be checked for years
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: inspectionRequested$ 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(), canAddValidationInfo()Whether signing a field, certifying, drawing a mark into a field without signing, reading the signed bytes, and adding validation data are allowed. Permissions
canFinish()Whether finish() has a field to sign: a signature field the user may sign that isn’t signed yet. Sign as the last step
getSettings(), updateSettings(changes), resetSettings()Reads the settings, changes them while the app runs, or goes back to what you registered. In a component, use inject(EpdfSignature).settings(). 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#

Every value is a signal on inject(EpdfSignature): read it in a template or a computed(), and your view updates when it changes. The method in the last column reads the same value once.

FieldWhat it isRead once
signatures()The signed fields, in document order, each with its verdict once checkedlistSignatures()
protection()What the document’s signatures allow, or null before they’re readgetProtection()
target()The field the next mark goes to, or nullgetTarget()
busy()Whether a signing or a fill is runningisBusy()
pending()A 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()
status()Whether 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 inject(EpdfSignature).settings() gives you the current settings.

SettingWhat it doesDefault
signingKeyThe signer, or a function that returns one when someone signsnone
timestampAuthorityThe timestamp authority: every signature the plugin seals carries its timestampnone
revocationWhere revocation answers come from: every signature the plugin seals gets its validation data right after. Needs trustnone
documentTimestampAdd a document timestamp after the validation data. Needs timestampAuthorityfalse
modeWhat a mark does in a field: 'sign', 'visual', 'finish' or 'ask''sign' with a key, else 'visual'
trustThe certificates you trust: for checking signatures, and for the timestamps you sealnone
allowCertifyLet a first signature be a certification, which sets what stays allowedfalse

Events#

save-warning.ts
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { EpdfSignature } from '@embedpdf/angular/signature';
import { showWarning } from './warnings';

@Component({ selector: 'app-save-warning', template: '' })
export class SaveWarning {
  constructor() {
    inject(EpdfSignature)
      .invalidationPredicted$.pipe(takeUntilDestroyed())
      .subscribe(() => showWarning('Saving this change will break a signature.'));
  }
}
EventFires whenCarries
signed$A field was signed, whoever signed itfield, result, origin
filled$, cleared$A mark was drawn into a field, or put into an image field; or removedfield
validated$The signatures were checkedverdicts
protectionChanged$What the signatures allow changedprotection
invalidationPredicted$A change would break a signature once savedfield, detail
targetChanged$A field became the target, or the target was clearedfield (null when cleared)
signRequested$In 'ask' mode, a mark was dropped on a fieldfield, mark
inspectionRequested$A signed field was clickedfield
settingsChanged$The settings changedsettings, changedKeys

result is the { signature, version, protection } that sign() resolves. “Sign here” in a form says what to show for the last three.

Permissions#

PermissionWhat it allowsCheck
doc.signSigningsignature.canSign(field)
doc.signAdding validation data and a document timestampsignature.canAddValidationInfo()
doc.sign.certifySigning a certificationsignature.canCertify()
doc.signDrawing a mark into a field without signingsignature.canFill(field)
doc.downloadReading the exact bytes a signature coverssignature.canReadRevision()

A mark in a signature field is its signer’s to place, so drawing one takes what signing takes. A user with a fields:sign permission for one group signs that group’s fields only, and draws marks only into them, so the checks take the field. See Signers and groups. On a signed document, the engine also refuses what its signatures forbid: canSign(field) and canFill(field) are false for a signature field an earlier signature locked. signature.canFinish() reads the same permissions over every signature field: it’s true while one the user may sign is still unsigned.

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.