Building forms
The form plugin can also add fields to a PDF, and change or remove the ones it has, so people can turn any document into a form. Switch to design mode, pick a field tool, and click or drag on the page:
import { Component, inject } from '@angular/core';
import { EpdfInteraction } from '@embedpdf/angular/interaction';
@Component({
selector: 'app-field-palette',
template: `
@for (tool of tools; track tool.id) {
<button
[attr.aria-pressed]="interaction.activeToolId() === tool.id"
(click)="interaction.activateTool(tool.id)"
>
{{ tool.label }}
</button>
}
`,
})
export class FieldPalette {
protected readonly interaction = inject(EpdfInteraction);
protected readonly tools = [
{ id: 'form-text', label: 'Text' },
{ id: 'form-checkbox', label: 'Checkbox' },
{ id: 'form-radio', label: 'Radio button' },
{ id: 'form-combobox', label: 'Dropdown' },
{ id: 'form-listbox', label: 'List' },
{ id: 'form-signature', label: 'Signature' },
];
}Building needs the annotation plugin next to the form plugin: in design mode, fields are boxes you select, move, resize and style like any annotation.
| Tool | Places | A click makes |
|---|---|---|
form-text | A text box | 160 × 24 |
form-checkbox | A checkbox | 18 × 18 |
form-radio | A radio button | 18 × 18 |
form-combobox | A dropdown | 140 × 24 |
form-listbox | A list | 140 × 72 |
form-button | A push button | 100 × 28 |
form-signature | A field someone signs later | 160 × 48 |
A see-through preview of the field follows the pointer, drawn as the field will be, so people see where it lands before they click. Drag instead of clicking for another size. The tool stays active, so placing ten checkboxes is ten clicks.
Loading live preview…
import {
ChangeDetectionStrategy,
Component,
computed,
effect,
inject,
untracked,
ViewEncapsulation,
} from '@angular/core';
import { EpdfDocument, 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 { EpdfInteraction, withInteraction } from '@embedpdf/angular/interaction';
import { EpdfAnnotationLayer, withAnnotation } from '@embedpdf/angular/annotation';
import { EpdfForm, EpdfFormLayer, withForm } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';
const registration = async (): Promise<OpenInput> => {
const response = await fetch('https://www.embedpdf.com/pdfs/registration.pdf');
return { kind: 'bytes', id: 'registration', bytes: new Uint8Array(await response.arrayBuffer()) };
};
const FIELD_TOOLS = [
['form-text', 'Text'],
['form-checkbox', 'Checkbox'],
['form-radio', 'Radio button'],
['form-combobox', 'Dropdown'],
['form-listbox', 'List'],
['form-signature', 'Signature'],
] as const;
@Component({
selector: 'demo-root',
imports: [
EpdfDocumentGate,
EpdfStage,
EpdfPageTemplate,
EpdfRenderLayer,
EpdfAnnotationLayer,
EpdfFormLayer,
],
providers: [
provideEmbedPdf(
{ engine: () => localEngine(), initialDocuments: [{ source: registration }] },
withStage(),
withRender(),
withInteraction(),
// Building forms needs the annotation plugin: in design mode, fields are boxes like any annotation.
withAnnotation(),
withForm(),
),
],
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrl: './designer.css',
encapsulation: ViewEncapsulation.None,
template: `
<ng-container *epdfDocumentGate="let document; fallback: loading">
@if (!form.canDesign()) {
<p class="readout">This document's form can't be changed.</p>
} @else {
<div class="toolbar">
<div class="segments">
<button
type="button"
class="segment"
[attr.aria-pressed]="filling()"
(click)="interaction.activateTool('pointer')"
>
Fill in
</button>
<button
type="button"
class="segment"
[attr.aria-pressed]="!filling()"
(click)="interaction.activateTool('form-edit')"
>
Design
</button>
</div>
@for (tool of tools; track tool[0]) {
<button
type="button"
class="button"
[attr.aria-pressed]="interaction.activeToolId() === tool[0]"
(click)="interaction.activateTool(tool[0])"
>
{{ tool[1] }}
</button>
}
<output class="readout">
{{ form.fields().length }} fields: click the page to place another
</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 form = inject(EpdfForm);
protected readonly interaction = inject(EpdfInteraction);
protected readonly tools = FIELD_TOOLS;
private readonly document = inject(EpdfDocument);
private started = false;
/** The pointer fills the form in; every other tool here designs it. */
protected readonly filling = computed(() => this.interaction.activeToolId() === 'pointer');
constructor() {
// Start with the text tool picked: the printed form has boxes, but no fields yet.
effect(() => {
if (this.document.status() !== 'ready' || this.started) return;
this.started = true;
untracked(() => this.interaction.activateTool('form-text'));
});
}
}Try it: the form was printed without fields. Click a printed box to put a text field on it, pick another kind for the circles, then press Fill in to type in your form.
On a turned page#
On a page that is shown turned, such as a scan saved sideways, a field is placed the way its
author sees the page: a click makes the tool’s size as the page shows it, and the field is turned
so that what’s typed into it reads upright there. The turn is saved with the field as a quarter
turn, the one turn a PDF form field can hold, so every PDF app shows it and fills it in the same
way. upright: false on a tool places its fields along the page instead; see
Rotated pages.
Turn the page, not the view, before you place fields: a page turned with
pageEdit.rotateBy() is saved with the document, and a view rotation is this
session’s only. Turn pages before the first signature too, since turning a page afterwards is a
change to a signed document.
Design mode#
The form-edit tool is design mode: fields stop being fillable and become boxes you can select, move
and resize. The pointer tool makes them fillable again:
interaction.activateTool('form-edit'); // design the form
interaction.activateTool('pointer'); // fill it inIn design mode the form lends its boxes to the annotation plugin, which selects, moves, resizes,
restyles, reorders and deletes them with its own tools, next to the annotations. Every edit of a box
is still the form’s: its place or look is updateWidget(), and deleting every box of a field
deletes the field. A drag of two fields and a stamp is one change: one request, and one step to
undo. Like every change, it shows at once and the engine’s answer follows.
A field just placed is selected at once, before the engine answers, and the tool goes back to
form-edit rather than the default pointer, so design mode goes on. Without canDesign() nothing is
lent: the fields stay fillable boxes the annotation tools leave alone.
Place fields for a signer#
When a form goes to several people, each field belongs to one of them: it’s in their group. Tell the document who its groups are, then say who the next fields are for:
form.setDesignGroup('buyer'); // fields placed with a tool are Dana'simport { Component, inject } from '@angular/core';
import { EpdfForm } from '@embedpdf/angular/form';
import { EpdfInteraction } from '@embedpdf/angular/interaction';
@Component({
selector: 'app-sender-toolbar',
template: `
@for (group of form.groups(); track group.id) {
<button
[attr.aria-pressed]="form.designGroup() === group.id"
[disabled]="!form.canSetGroup(group.id)"
(click)="form.setDesignGroup(group.id)"
>
<i [style.background]="group.color"></i> {{ group.label ?? group.id }}
</button>
}
@for (tool of tools; track tool.id) {
<button
[attr.aria-pressed]="interaction.activeToolId() === tool.id"
(click)="interaction.activateTool(tool.id)"
>
{{ tool.label }}
</button>
}
`,
})
export class SenderToolbar {
protected readonly form = inject(EpdfForm);
protected readonly interaction = inject(EpdfInteraction);
protected readonly tools = [
{ id: 'form-text', label: 'Text' },
{ id: 'form-checkbox', label: 'Checkbox' },
{ id: 'form-signature', label: 'Signature' },
];
}While you design, every field shows in its group’s color. A field placed with a tool goes into
the group you set, which the form’s state has as form.designGroup(). With null, where it starts, it names
no group, and a placed field is in none.
Putting a field in a group other than your own takes the fields:set-group permission for that
group, and form.canSetGroup(groupId) says whether the user has it. Turn off the signers a user
can’t place for: setDesignGroup() refuses a group they may not put a field in, as create(),
update() and moveToGroup() do. A field in no group needs no such permission: whoever may
design the form may leave a field in none, or take it out of its group.
Loading live preview…
import {
ChangeDetectionStrategy,
Component,
effect,
type ElementRef,
inject,
input,
signal,
viewChild,
ViewEncapsulation,
} from '@angular/core';
import {
EpdfDocument,
EpdfDocumentGate,
EpdfDocuments,
EpdfViewer,
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 { EpdfInteraction, withInteraction } from '@embedpdf/angular/interaction';
import { EpdfAnnotationLayer, withAnnotation } from '@embedpdf/angular/annotation';
import { EpdfAnchored } from '@embedpdf/angular/anchored';
import { EpdfForm, EpdfFormLayer, withForm } from '@embedpdf/angular/form';
import { EpdfSignature, withSignature } from '@embedpdf/angular/signature';
import { localEngine } from '@embedpdf/engine';
const engine = localEngine();
const loan = async (): Promise<OpenInput> => {
const response = await fetch('https://www.embedpdf.com/pdfs/loan.pdf');
return { kind: 'bytes', id: 'loan', bytes: new Uint8Array(await response.arrayBuffer()) };
};
// What each person may do, as permissions: the sender places fields for both signers, and each
// signer fills in and signs their own.
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:group=borrower',
'fields:set-group:group=approver',
],
},
borrower: {
name: 'Dana Smith',
scope: [...see, 'fields:fill:group=borrower', 'fields:sign:group=borrower'],
},
approver: {
name: 'Ada Lovelace',
scope: [...see, 'fields:fill:group=approver', 'fields:sign:group=approver'],
},
};
type Person = keyof typeof people;
// 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' }, // a color is picked for it
];
const FIELD_TOOLS = [
['form-text', 'Text'],
['form-checkbox', 'Checkbox'],
['form-signature', 'Signature'],
] as const;
/** The sender picks who the next field is for, then a tool, and clicks the page. */
@Component({
selector: 'demo-sender-toolbar',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="toolbar">
<span class="label">Next field is for</span>
@for (group of form.groups(); track group.id) {
<button
type="button"
class="button"
[attr.aria-pressed]="form.designGroup() === group.id"
[disabled]="!form.canSetGroup(group.id)"
(click)="form.setDesignGroup(group.id)"
>
<i class="swatch" [style.background]="group.color"></i>{{ group.label ?? group.id }}
</button>
}
<span class="divider"></span>
@for (tool of tools; track tool[0]) {
<button
type="button"
class="button"
[attr.aria-pressed]="interaction.activeToolId() === tool[0]"
(click)="interaction.activateTool(tool[0])"
>
{{ tool[1] }}
</button>
}
</div>
`,
})
export class SenderToolbar {
protected readonly form = inject(EpdfForm);
protected readonly interaction = inject(EpdfInteraction);
protected readonly tools = FIELD_TOOLS;
constructor() {
// Start by placing text fields for the first signer.
this.form.setDesignGroup('borrower');
this.interaction.activateTool('form-text');
}
}
/** A signer sees whose field is whose: theirs stand out, and the others take no input. */
@Component({
selector: 'demo-signer-legend',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="toolbar">
@for (group of form.groups(); track group.id) {
<span class="legend">
<i class="swatch" [style.background]="group.color"></i>
{{ group.label ?? group.id }}: {{ count(group.id) }}
</span>
}
<output class="readout">
{{ people[person()].name }} fills in the fields in their color
</output>
</div>
`,
})
export class SignerLegend {
readonly person = input.required<Person>();
protected readonly form = inject(EpdfForm);
protected readonly people = people;
/** How many fields are in a group. */
protected count(groupId: string) {
return this.form.fields().filter((field) => field.groupId === groupId).length;
}
}
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.
*/
@Component({
selector: 'demo-sign-card',
imports: [EpdfAnchored],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@if (signature.target()) {
<epdf-anchored [anchor]="anchor()" placement="bottom-start" [gap]="8">
<div
#card
class="sign-card"
role="dialog"
aria-label="Draw your signature"
tabindex="-1"
(keydown.escape)="close()"
>
<canvas
#pad
class="sign-pad"
width="240"
height="100"
(pointerdown)="start($event)"
(pointermove)="draw($event)"
></canvas>
<div class="sign-actions">
<button type="button" class="button" (click)="close()">Cancel</button>
<button type="button" class="button" [disabled]="!drawn()" (click)="sign()">
Sign
</button>
</div>
</div>
</epdf-anchored>
}
`,
})
export class SignCard {
private readonly form = inject(EpdfForm);
protected readonly signature = inject(EpdfSignature);
protected readonly anchor = this.form.widgetAnchorOf(() => {
const target = this.signature.target();
return target ? (this.form.getWidgets(target)[0]?.ref ?? null) : null;
});
protected readonly drawn = signal(false);
private readonly card = viewChild<ElementRef<HTMLDivElement>>('card');
private readonly pad = viewChild<ElementRef<HTMLCanvasElement>>('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 signing, and put the cursor back on the field.
protected close() {
const field = this.signature.target();
this.signature.setTarget(null);
if (field) this.form.focus(field);
}
// The drawing goes into the field as a picture.
protected sign() {
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);
});
}
}
/** Names the open document's groups, and shows the sender's toolbar or a signer's legend. */
@Component({
selector: 'demo-toolbar',
imports: [SenderToolbar, SignerLegend],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<!-- The open document says what its user may do: it is the sender's while they may
design it. -->
@if (form.canDesign()) {
<demo-sender-toolbar />
} @else {
<demo-signer-legend [person]="person()" />
}
`,
})
export class Toolbar {
readonly person = input.required<Person>();
protected readonly form = inject(EpdfForm);
constructor() {
// Tell the open document who its groups are.
this.form.setGroups(signers);
}
}
@Component({
selector: 'demo-root',
imports: [
EpdfDocumentGate,
EpdfStage,
EpdfPageTemplate,
EpdfRenderLayer,
EpdfAnnotationLayer,
EpdfFormLayer,
Toolbar,
SignCard,
],
providers: [
provideEmbedPdf(
{
engine,
scope: people.sender.scope,
initialDocuments: [{ source: loan, name: 'equipment-loan.pdf' }],
},
withStage(),
withRender(),
withInteraction(),
withAnnotation(),
withForm(),
// An empty signature field becomes a button. With no key, a mark is drawn into the field.
withSignature(),
),
],
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrl: './signers.css',
encapsulation: ViewEncapsulation.None,
template: `
<div class="toolbar">
<span class="label">Open the form as</span>
<div class="segments">
@for (each of everyone; track each) {
<button
type="button"
class="segment"
[attr.aria-pressed]="person() === each"
(click)="handOver(each)"
>
{{ people[each].name }}
</button>
}
</div>
</div>
<ng-container *epdfDocumentGate="let document; fallback: opening">
<demo-toolbar [person]="person()" />
<epdf-stage class="stage">
<ng-template epdfPage>
<epdf-render-layer />
<epdf-annotation-layer />
<epdf-form-layer />
</ng-template>
<demo-sign-card />
</epdf-stage>
</ng-container>
<ng-template #opening><p class="loading">Opening…</p></ng-template>
`,
})
export class App {
private readonly viewer = inject(EpdfViewer);
private readonly documents = inject(EpdfDocuments);
private readonly document = inject(EpdfDocument);
protected readonly people = people;
protected readonly everyone = Object.keys(people) as Person[];
protected readonly person = signal<Person>('sender');
// A document keeps the permissions it opened with, so the next person opens the saved form again.
protected async handOver(person: Person) {
if (person === this.person()) return;
this.person.set(person);
this.viewer.updateSettings({ scope: people[person].scope });
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' });
}
}Try it: as the sender, click the borrower’s Name box to place a text field for Dana, then pick Signature and click her Signature box. Pick Ada and do the same under “Approved by”: each field shows in its signer’s color. Then open the form as Dana. Her fields stand out, her name box takes her typing, and Ada’s show as the PDF has them. Click Dana’s signature field, or Tab to it and press Space, draw a signature in the card and press Sign.
The signers can sign because the example also has the signature plugin: an empty
signature field is a button, and pressing it makes the field the
target. The example’s card opens next to the target and places
the drawing in the field as a PNG, with signature.placeMark({ source: png }, { field }). With
no signing key, the mark is drawn into the field and nothing is sealed;
The key has what a real signature takes. Escape or Cancel closes the card
and puts the cursor back on the field.
A document keeps the permissions it opened with, so the example saves the form and opens it again for each person, with theirs.
Give fields to a signer#
A form made somewhere else, in Acrobat for example, arrives with its fields in no group. Move one
like any setting, and null takes it out of its group again:
await form.update(field.ref, { groupId: 'seller' });
await form.update(field.ref, { groupId: null }); // nobody'sOr move every selected field in one call, which is one step to undo:
import { Component, inject } from '@angular/core';
import { EpdfForm } from '@embedpdf/angular/form';
@Component({
selector: 'app-give-selected-to',
template: `
@if (form.selectedFields().length > 0) {
Give to
@for (group of form.groups(); track group.id) {
<button [disabled]="!form.canSetGroup(group.id)" (click)="give(group.id)">
<i [style.background]="group.color"></i> {{ group.label ?? group.id }}
</button>
}
}
`,
})
export class GiveSelectedTo {
protected readonly form = inject(EpdfForm);
protected give(groupId: string) {
void this.form.moveToGroup(
this.form.selectedFields().map((field) => field.ref),
groupId,
);
}
}form.selectedFields() in the form’s state has every field with a selected box, and form.listSelectedFields()
reads it once. moveToGroup(fields, groupId) leaves out the fields already in the group, shows
the rest in their new color at once, and resolves { fields } as they are now. With null it
takes the fields out of their group.
Change a field’s settings#
form.selectedField() is the field of the selected box, for a settings panel:
import { Component, inject } from '@angular/core';
import { EpdfForm } from '@embedpdf/angular/form';
@Component({
selector: 'app-field-settings',
template: `
@if (form.selectedField(); as field) {
<input #nameInput [value]="field.name" (blur)="form.update(field.ref, { name: nameInput.value })" />
<label>
<input
#requiredInput
type="checkbox"
[checked]="field.required"
(change)="form.update(field.ref, { required: requiredInput.checked })"
/>
Required
</label>
}
`,
})
export class FieldSettings {
protected readonly form = inject(EpdfForm);
}update() takes only what you change, with the same settings a field reads:
| Setting | What it is |
|---|---|
name | Its own part of its name: renaming customer.email to phone makes customer.phone |
required | PDF apps ask for a value before the form is submitted |
readOnly | People can’t change the value |
alternateName | The tooltip, also read by screen readers |
defaultValue | What a reset puts back |
options | For a dropdown or list: { label, value } pairs |
maxLength, multiline, password, comb | For a text box |
groupId | The group it’s in: who fills it in. Give fields to a signer |
getFieldSettings(ref) describes a field’s settings for a panel you draw without knowing the
field’s kind: { properties, values }, each property a key (what update() takes), a control
(text, flag, number, choice, choices or options), and a label in English with its
translation key, labelKey (form.settings.tooltip), in display order. A choice‘s options are
the field’s own values, shown as they are. While the document has groups, groupId is one of the
settings: a choice whose options are the ids of the groups the user may put the field in. Show
each with its group’s label, from the form’s groups; none of them, null, takes the field out
of its group.
A field’s look, such as its border, background and font, belongs to its box: change it like any
annotation’s, with the style panel, or from code with
form.updateWidget(widget.ref, { color: '#1d4ed8' }).
Loading live preview…
import {
ChangeDetectionStrategy,
Component,
effect,
inject,
untracked,
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 { EpdfInteraction, withInteraction } from '@embedpdf/angular/interaction';
import { EpdfAnnotation, EpdfAnnotationLayer, withAnnotation } from '@embedpdf/angular/annotation';
import { EpdfForm, EpdfFormLayer, toFieldRef, withForm } from '@embedpdf/angular/form';
import type { FormField } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';
const forms = async (): Promise<OpenInput> => {
const response = await fetch('https://www.embedpdf.com/pdfs/forms.pdf');
return { kind: 'bytes', id: 'forms', bytes: new Uint8Array(await response.arrayBuffer()) };
};
@Component({
selector: 'demo-root',
imports: [
EpdfDocumentGate,
EpdfStage,
EpdfPageTemplate,
EpdfRenderLayer,
EpdfAnnotationLayer,
EpdfFormLayer,
],
providers: [
provideEmbedPdf(
{ engine: () => localEngine(), initialDocuments: [{ source: forms }] },
withStage(),
withRender(),
withInteraction(),
withAnnotation(),
withForm(),
),
],
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrl: './field-settings.css',
encapsulation: ViewEncapsulation.None,
template: `
<ng-container *epdfDocumentGate="let document; fallback: loading">
<div class="viewer">
<epdf-stage class="stage">
<ng-template epdfPage>
<epdf-render-layer />
<epdf-annotation-layer />
<epdf-form-layer />
</ng-template>
</epdf-stage>
<!-- What a settings panel shows for the selected field, and changes with update(). -->
@if (form.selectedField(); as field) {
<div class="panel">
<label class="setting">
Name
<input #name class="input" [value]="field.name" (blur)="rename(field, name.value)" />
</label>
<label class="setting">
Tooltip
<input
#tooltip
class="input"
[value]="field.alternateName ?? ''"
(blur)="form.update(field.ref, { alternateName: tooltip.value || null })"
/>
</label>
<label class="check">
<input
#required
type="checkbox"
[checked]="field.required"
(change)="form.update(field.ref, { required: required.checked })"
/>
Required
</label>
<label class="check">
<input
#readOnly
type="checkbox"
[checked]="field.readOnly"
(change)="form.update(field.ref, { readOnly: readOnly.checked })"
/>
Read-only
</label>
<button type="button" class="button" (click)="form.delete(field.ref)">
Remove the field
</button>
</div>
} @else {
<p class="panel hint">Select a field on the page.</p>
}
</div>
</ng-container>
<ng-template #loading><p class="loading">Loading…</p></ng-template>
`,
})
export class App {
protected readonly form = inject(EpdfForm);
private readonly annotation = inject(EpdfAnnotation);
private readonly interaction = inject(EpdfInteraction);
private started = false;
constructor() {
// On load: design mode, with the name field selected.
effect(() => {
if (this.form.status() !== 'ready' || this.started) return;
this.started = true;
untracked(() => {
this.interaction.activateTool('form-edit');
const widget = this.form.get(toFieldRef('name'))?.widgets[0]?.ref;
if (widget) this.annotation.selection.select([widget]);
});
});
}
protected rename(field: FormField, value: string) {
const name = value.trim();
if (name && name !== field.name) void this.form.update(field.ref, { name });
}
}Turn a field#
A field turns by quarter turns, in two ways:
// The whole box: it stands the other way, and its contents turn with it
await annotation.selection.rotateBy(90); // -90 the other way; resetRotation() for upright
// Only its contents: the box stays where it stands, as Acrobat's Orientation does
await annotation.selection.update((widget) => orientationPatch(widget, 90));rotateBy() turns the selected fields as it turns a stamp, about each box’s middle (several
together turn about their middle). A field near the edge of its page stays on the page: where the
turn would carry it past the edge, it lands against the edge. A field has no rotation handle,
because a quarter turn is all it can hold. orientationPatch() comes with the annotation plugin:
it gives the box and rotation that turn a field’s contents where it stands.
The style panel lists the second as orientation for a
selection of fields: a choice of '0', '90', '180' and '270', clockwise. Without a
selection, form.updateWidget(widget.ref, orientationPatch(widget, 90)) does the same for one
box, and form.updateWidget(widget.ref, { rotation: 90 }) turns the whole box. A box reads its
turn as rotation, with box, the frame its contents are laid out in, and rect, where it
stands; see Turned fields.
Add fields from code#
create() takes the same settings the engine takes, with the page and the box for each place the
field shows:
const { field } = await form.create({
kind: 'combobox',
name: 'country',
options: [
{ label: 'Netherlands', value: 'NL' },
{ label: 'Belgium', value: 'BE' },
],
widgets: [{ page: page.ref, rect: { x: 72, y: 252, width: 148, height: 20 } }],
});A radio group is one field with a box per button, each with the value it stands for:
await form.create({
kind: 'radio',
name: 'plan',
widgets: [
{ page: page.ref, rect: { x: 72, y: 136, width: 16, height: 16 }, exportValue: 'monthly' },
{ page: page.ref, rect: { x: 72, y: 166, width: 16, height: 16 }, exportValue: 'yearly' },
],
});A field placed with a tool gets a name like text_1; rename it in your settings panel. Every
kind’s settings are on Creating form fields.
Loading live preview…
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
signal,
viewChild,
ViewEncapsulation,
} from '@angular/core';
import { EpdfDocument, EpdfDocumentGate, 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 { EpdfForm, EpdfFormLayer, withForm } from '@embedpdf/angular/form';
import type { FormField } from '@embedpdf/angular/form';
import { localEngine } from '@embedpdf/engine';
const registration = async (): Promise<OpenInput> => {
const response = await fetch('https://www.embedpdf.com/pdfs/registration.pdf');
return { kind: 'bytes', id: 'registration', bytes: new Uint8Array(await response.arrayBuffer()) };
};
// The printed boxes are the fields' look: a new field only sets its text size.
const look = { fontSize: 11 };
// The printed table of group tickets: a row every 36 points from the top at 470, with a country
// box at x 96 and a circle for each ticket at x 330 and 430.
const rowTop = (row: number) => 470 + row * 36;
/** A dropdown in a row's country box. */
function addDropdown(form: EpdfForm, page: PageRef, row: number) {
return form.create({
kind: 'combobox',
name: `country_${row + 1}`,
options: [
{ label: 'Netherlands', value: 'NL' },
{ label: 'Belgium', value: 'BE' },
{ label: 'Germany', value: 'DE' },
],
widgets: [{ page, rect: { x: 96, y: rowTop(row), width: 160, height: 24 }, ...look }],
});
}
/** A radio group in a row's two circles: one field, a widget per circle, each with its value. */
function addRadioGroup(form: EpdfForm, page: PageRef, row: number) {
const y = rowTop(row) + 4;
return form.create({
kind: 'radio',
name: `ticket_${row + 1}`,
widgets: [
{ page, rect: { x: 330, y, width: 16, height: 16 }, exportValue: 'one-day', ...look },
{ page, rect: { x: 430, y, width: 16, height: 16 }, exportValue: 'both-days', ...look },
],
});
}
@Component({
selector: 'demo-root',
imports: [EpdfDocumentGate, EpdfStage, EpdfPageTemplate, EpdfRenderLayer, EpdfFormLayer],
providers: [
provideEmbedPdf(
{ engine: () => localEngine(), initialDocuments: [{ source: registration }] },
withStage(),
withRender(),
withInteraction(),
withForm(),
),
],
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrl: './create.css',
encapsulation: ViewEncapsulation.None,
template: `
<ng-container *epdfDocumentGate="let document; fallback: loading">
<div class="toolbar">
<button
type="button"
class="button"
[disabled]="!page() || rowFor('combobox') >= 5"
(click)="add(addDropdown, 'combobox')"
>
Add a dropdown
</button>
<button
type="button"
class="button"
[disabled]="!page() || rowFor('radio') >= 5"
(click)="add(addRadioGroup, 'radio')"
>
Add a radio group
</button>
<button type="button" class="button" [disabled]="!last()" (click)="removeLast()">
Remove the last
</button>
<output class="readout">{{ names() || 'No fields in the table yet' }}</output>
</div>
<epdf-stage class="stage">
<ng-template epdfPage>
<epdf-render-layer />
<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 document = inject(EpdfDocument);
private readonly stage = viewChild(EpdfStage);
protected readonly addDropdown = addDropdown;
protected readonly addRadioGroup = addRadioGroup;
protected readonly page = computed(() => this.document.pages()[0]?.ref); // the printed form
private readonly added = signal<FormField[]>([]);
protected readonly last = computed(() => this.added().at(-1));
protected readonly names = computed(() =>
this.added()
.map((field) => field.name)
.join(', '),
);
/** Each kind of field fills its column from the top: the next row that hasn't got one. */
protected rowFor(kind: FormField['kind']) {
return this.added().filter((field) => field.kind === kind).length;
}
protected async add(addField: typeof addDropdown, kind: FormField['kind']) {
const page = this.page();
if (!page) return;
const { field } = await addField(this.form, page, this.rowFor(kind));
this.added.update((fields) => [...fields, field]);
this.stage()?.reveal(page, { rect: this.form.getWidget(field.widgets[0])!.rect });
}
protected async removeLast() {
const last = this.last();
if (!last) return;
await this.form.delete(last.ref);
this.added.update((fields) => fields.slice(0, -1));
}
}Try it: add a dropdown and a radio group: each goes into the next row of the printed table.
One more button for a group#
addWidget(ref) shows a field in one more place: for a radio group a new choice, for a checkbox a
box that checks together with the others.
const { widget } = await form.addWidget(plan.ref);
annotation.selection.select([widget.ref]); // in design mode, so it can be draggedWithout a place, it goes next in line: below the last button if they stand in a column, beside it
if in a row, at the same size and the same spacing, starting a new column where the page ends. It
looks like the field’s last button, and a radio group’s new choice gets the next free Choice<n>.
Pass what you want instead: form.addWidget(plan.ref, { rect, exportValue: 'yearly' }) takes
everything an entry of create()‘s widgets takes.
Copy fields#
duplicateWidgets() copies boxes, as Duplicate does in a designer. What a copy becomes follows
from what its box is:
- A radio button is one answer to a question. Its copy is another button in the same group,
with the next free
Choice<n>as its value. - Any other box is a whole question. Its copy is a new field, named after the original:
emailbecomesemail_2.
// another button in the group, below the one it copies
await form.duplicateWidgets([button.ref], {
offset: { x: 0, y: 24 },
});
// a new text field beside the original
const { fields } = await form.duplicateWidgets([box.ref], {
offset: { x: 10, y: 10 },
});Boxes of one field that are copied together become one new field. duplicate() copies whole
fields instead: a radio group becomes a new group with the same buttons and the same values.
const { fields } = await form.duplicate([plan.ref], {
offset: { x: 0, y: 80 },
});A new field has its original’s settings, scripts and default value. It doesn’t have its answer:
it starts empty, as a new field does. Pass values: true to copy the answer too. A signature
never comes along.
| Option | What it does | Default |
|---|---|---|
page | The page the copies go on, as a ref or an index. | each on its own |
offset | How far each copy moves: { x, y } in page points. | { x: 0, y: 0 } |
values | Whether a new field gets its original’s answer. | false |
Both resolve { fields, widgets, dropped }: the fields that were made or got a new button, the
new boxes, and what was left out. A copy leaves out what
an import leaves out: a field of a kind the
engine doesn’t know, a script when canWriteScripts() is false, an action it can’t write. A box
in no field is left out too.
One call makes at most 10,000 new fields: the engine’s item
limit, which a server can change. More is refused with
invalid-input, and nothing is copied.
In design mode, Duplicate the selection does this for the selected boxes, together with the annotations selected beside them.
Scripts and calculations#
A field’s scripts go in actions when you create or change it: a calculated total, a formatted
amount, a check on what the user typed. The viewer runs them while the user fills the form in.
await form.update(total.ref, {
actions: {
calculate: {
type: 'javascript',
script: 'event.value = this.getField("subtotal").value * 1.21;',
},
},
});
await form.reorderCalculations([tax.ref], { before: total.ref });A calculate script puts the field at the end of the order calculations run in;
reorderCalculations() moves it. Writing a script needs canWriteScripts(). See
Scripts and calculations.
A box can do something when it’s clicked, too, such as reset the form: give its entry of
widgets in create() its actions. A script, a submit or a web link there needs
canWriteScripts() as well. See Widget actions.
A push button (kind: 'pushbutton') is a box that only does that, with a caption; see
A push button.
Remove a field#
await form.delete(field.ref);This removes the field and every box it has. To remove one box of a field that shows in several places,
such as a reference number on every page, use form.deleteWidget(widget.ref). It resolves the field
as it is now. In design mode, deleting the selection does the same: one box goes from its field, and
a field whose every box is selected goes whole.
Every building method shows its change at once, is one step to undo, and resolves once the engine answered.
Methods#
What inject(EpdfForm) gives you for building forms. Reading, filling and the form’s state are on
Filling forms.
| Method | What it does |
|---|---|
create(draft) | Adds a field, with a box for each place it shows. Resolves { field }. Add fields from code |
update(ref, patch) | Changes a field’s settings; pass only what changes. Resolves { field }. Change a field’s settings |
addWidget(ref, placement?) | Shows a field in one more place: a radio group’s next choice, a checkbox’s next box. Resolves { field, widget }. One more button for a group |
duplicate(fields, options?) | Copies whole fields, each as a new field. Resolves { fields, widgets, dropped }. Copy fields |
duplicateWidgets(widgets, options?) | Copies boxes: a radio button joins its group, any other box becomes a new field. Resolves { fields, widgets, dropped }. Copy fields |
delete(ref) | Removes a field and every box it has. Remove a field |
updateWidget(widget, patch) | Changes one box’s place, turn or look; pass only what changes. Resolves { widget }. Change a field’s settings, Turn a field |
getFieldSettings(ref) | A field’s settings described for a panel: { properties, values }, or null. Change a field’s settings |
deleteWidget(widget) | Removes one box from its page, and from its field when it has one. Resolves { field }, or { field: null } for a box in no field. Remove a field |
removeWidget(ref, widget) | Takes one box out of its field; it stays on the page, in no field, until deleteWidget() removes it |
reorderCalculations(fields, position) | Moves fields in the order calculate scripts run in. Resolves { calculationOrder }. Scripts and calculations |
repair(options?) | Fixes a form other PDF apps read differently, such as fields missing from the form’s list, and resolves what it fixed. See Repair a broken form. |
canDesign() | Whether adding, changing and removing fields is allowed. Permissions |
setDesignGroup(groupId) | Says who the next fields are for: a field placed with a tool goes into this group; with null it is in none. Fires designGroupChanged$. Place fields for a signer |
moveToGroup(fields, groupId) | Puts fields in a group, or with null takes them out of theirs, as one step to undo. Resolves { fields }. Give fields to a signer |
canSetGroup(groupId) | Whether the user may put a field in that group. Place fields for a signer |
canRestoreAttribution() | Whether an import may keep who created its fields, instead of naming the importing user. Permissions |
canWriteScripts() | Whether scripts, submit buttons and links may be written into fields and their boxes. Permissions |
Every method that returns a promise also takes a signal in its options, to cancel it.
Events#
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { EpdfForm } from '@embedpdf/angular/form';
import { selectField } from './editor';
@Component({ selector: 'app-select-new-fields', template: '' })
export class SelectNewFields {
constructor() {
inject(EpdfForm)
.fieldCreated$.pipe(takeUntilDestroyed())
.subscribe(({ field }) => selectField(field));
}
}| Event | Fires when | Carries |
|---|---|---|
fieldCreated$ | A field was added | field, origin |
fieldUpdated$ | A field’s settings changed | field, origin |
fieldDeleted$ | A field was removed | ref, origin |
designGroupChanged$ | The group new fields are placed for changed | groupId |
Permissions#
| Permission | What it allows | Check |
|---|---|---|
doc.forms.modify | Adding, changing, removing and repairing fields | form.canDesign() |
doc.forms.import | Importing fields with who created them | form.canRestoreAttribution() |
doc.forms.script | Writing scripts, submit buttons and links into fields and boxes | form.canWriteScripts() |
fields:set-group | Putting a field in a group other than your own | form.canSetGroup(groupId) |
Hide the field tools when canDesign() is false, and the script, submit and link options of a
field’s or a box’s actions when canWriteScripts() is false. Scripts already in the form run either way.
Good to know#
Fields and boxes#
A field is the data: its name, its value, its settings. A widget is a box where the field shows on a page. Most fields have one; a radio group has one per button, and a field can show on several pages, all with the same value.
Signature fields#
A signature field is a place for someone to sign later. Signing it is on Signatures.
Your feedback goes directly to the documentation team.