import { ChangeDetectionStrategy, Component, computed, effect, type ElementRef, inject, input, output, signal, untracked, viewChild, ViewEncapsulation, } from '@angular/core'; import { EpdfDocument, EpdfDocumentGate, EpdfDocuments, EpdfViewer, provideEmbedPdf, } from '@embedpdf/angular/runtime'; import type { OpenInput, PageRef } 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 { EpdfAnchored } from '@embedpdf/angular/anchored'; import { EpdfForm, EpdfFormLayer, withForm } from '@embedpdf/angular/form'; import type { FormField, FormFieldDraft } from '@embedpdf/angular/form'; import { createTestSigner, EpdfSignature, withSignature } from '@embedpdf/angular/signature'; import { localEngine } from '@embedpdf/engine'; 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' }), }; // [!doc-source loan] const loan = async (): Promise => { const response = await fetch('https://www.embedpdf.com/pdfs/loan.pdf'); return { kind: 'bytes', id: 'loan', bytes: new Uint8Array(await response.arrayBuffer()) }; }; // [!/doc-source] // 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; // 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. */ @Component({ selector: 'demo-prepare', changeDetection: ChangeDetectionStrategy.OnPush, template: `
The sender is placing the fields…
`, }) export class Prepare { readonly done = output(); private readonly form = inject(EpdfForm); private readonly document = inject(EpdfDocument); private started = false; constructor() { effect(() => { const page = this.document.pages()[0]?.ref; // the printed form if (!page || this.started) return; this.started = true; untracked(() => void this.place(page)); }); } private async place(page: PageRef) { for (const draft of fieldsOn(page)) await this.form.create(draft); this.done.emit(); } } /** 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()`. */ @Component({ selector: 'demo-guide', changeDetection: ChangeDetectionStrategy.OnPush, template: `
@if (!signature.canFinish()) { {{ signed() }} @if (handsOver()) { } } @else { {{ people[person()].name }} {{ progress() }} @if (problems().length > 0) { Still to do: {{ problems().join(', ') }} } }
`, }) export class Guide { readonly person = input.required(); /** Whether the form goes to another signer once this one finished. */ readonly handsOver = input(false); readonly handOver = output(); protected readonly form = inject(EpdfForm); protected readonly signature = inject(EpdfSignature); protected readonly people = people; protected readonly agreed = signal(false); protected readonly problems = signal([]); protected readonly color = computed( () => signers.find((each) => each.id === this.person())?.color, ); /** The required fields, and the ones still empty. */ protected readonly check = computed(() => { this.form.fields(); // again when a field is filled in return this.form.validate(); }); protected readonly progress = computed(() => { const { required, missing } = this.check(); return `${required.length - missing.length} of ${required.length} filled in`; }); /** Who signed, and what the check of each signature says. */ protected readonly signed = computed(() => this.signature .signatures() .map((each) => `${each.signer?.name}: ${each.verdict?.summary ?? 'checking…'}`) .join(' · '), ); constructor() { // The signer starts: the app fills in what it knows, their name and today's date. void this.form.prefill(); // What Finish said is left stands until the form changes. effect(() => { this.form.fields(); this.problems.set([]); }); } // 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. protected async finish() { const person = this.person(); const result = await this.signature.finish({ signingKey: () => keys[person], signer: { reason: 'I agree to the terms of this loan' }, }); if (result.status === 'signed') return this.problems.set([]); this.problems.set([ ...result.missing.map(nameOf), ...result.invalid.map(({ field, message }) => `${nameOf(field)}: ${message ?? 'not valid'}`), ]); this.form.focus((result.missing[0] ?? result.invalid[0]!.field).ref); } } 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. */ @Component({ selector: 'demo-sign-card', imports: [EpdfAnchored], changeDetection: ChangeDetectionStrategy.OnPush, template: ` @if (signature.target()) { } `, }) export class SignCard { private readonly form = inject(EpdfForm); protected readonly signature = inject(EpdfSignature); private readonly row = computed(() => { const target = this.signature.target(); return target ? this.form.getWidgets(target)[0] : undefined; }); protected readonly anchor = this.form.widgetAnchorOf(() => this.row()?.ref ?? null); protected readonly hasMark = computed(() => this.row()?.hasMark ?? false); protected readonly drawn = signal(false); private readonly card = viewChild>('card'); private readonly pad = viewChild>('pad'); private last: Point | null = null; constructor() { // Each field starts with an empty pad, and the card takes the cursor, so Escape closes it. effect(() => { const target = this.signature.target(); const pad = this.pad()?.nativeElement; this.last = null; this.drawn.set(false); pad?.getContext('2d')?.clearRect(0, 0, pad.width, pad.height); if (target) this.card()?.nativeElement.focus(); }); } private pointOf(event: PointerEvent, canvas: HTMLCanvasElement): Point { const box = canvas.getBoundingClientRect(); return { x: event.clientX - box.left, y: event.clientY - box.top }; } protected start(event: PointerEvent) { const canvas = event.currentTarget as HTMLCanvasElement; canvas.setPointerCapture(event.pointerId); this.last = this.pointOf(event, canvas); } protected draw(event: PointerEvent) { const canvas = event.currentTarget as HTMLCanvasElement; const from = this.last; const ink = canvas.getContext('2d'); if (!from || !ink || !canvas.hasPointerCapture(event.pointerId)) return; const to = this.pointOf(event, canvas); this.last = to; ink.strokeStyle = INK; ink.lineWidth = 2; ink.lineCap = 'round'; ink.beginPath(); ink.moveTo(from.x, from.y); ink.lineTo(to.x, to.y); ink.stroke(); this.drawn.set(true); } // Close without a change, and put the cursor back on the field. protected close(field = this.signature.target()) { this.signature.setTarget(null); if (field) this.form.focus(field); } // The drawing goes into the field as a picture, in place of the one it holds. protected place() { const field = this.signature.target(); this.pad()?.nativeElement.toBlob(async (png) => { if (!field || !png) return; await this.signature.placeMark({ source: png }, { field }); this.form.focus(field); }); } // Take the mark out again: the field is empty, and still theirs to sign. protected async remove() { const field = this.signature.target(); if (!field) return; await this.signature.clearField(field); this.close(field); } } /** Names the open document's groups, and shows the sender's part or a signer's guide. */ @Component({ selector: 'demo-toolbar', imports: [Prepare, Guide], changeDetection: ChangeDetectionStrategy.OnPush, template: ` @if (form.canDesign()) { } @else if (signer(); as signer) { } `, }) export class Toolbar { readonly person = input.required(); readonly next = output(); protected readonly form = inject(EpdfForm); protected readonly signer = computed(() => { const person = this.person(); return person === 'sender' ? null : person; }); constructor() { // Tell the open document who its groups are. this.form.setGroups(signers); } } @Component({ selector: 'demo-root', imports: [ EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer, Toolbar, SignCard, ], providers: [ provideEmbedPdf( { engine, scope: people.sender.scope, identity: people.sender.identity, initialDocuments: [{ source: loan, name: 'equipment-loan.pdf' }], }, withStage(), withRender(), withInteraction(), withForm(), withSignature({ // 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), }, }), ), ], changeDetection: ChangeDetectionStrategy.OnPush, styleUrl: './signing-flow.css', encapsulation: ViewEncapsulation.None, template: `

Opening…

`, }) export class App { private readonly viewer = inject(EpdfViewer); private readonly documents = inject(EpdfDocuments); private readonly document = inject(EpdfDocument); protected readonly person = signal('sender'); // A document keeps who it opened for, so the next person opens the saved form again. protected async handOver() { const person = this.person() === 'sender' ? 'borrower' : 'approver'; if (person === this.person()) return; this.person.set(person); const { scope, identity } = people[person]; this.viewer.updateSettings({ scope, identity }); const id = this.document.id(); if (!id) return; const bytes = await this.documents.download(); await this.documents.close(id); await this.documents.open({ kind: 'bytes', bytes }, { name: 'equipment-loan.pdf' }); } }