Filling forms
Many PDFs are forms: text boxes, checkboxes, dropdowns, signature fields. Register formPlugin() and
put <FormLayer> in each page, and people can fill them in:
import { FormLayer, formPlugin } from '@embedpdf/react/form';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { Viewer } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { engine } from './pdf';
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), formPlugin()];
export function FormViewer() {
return (
<Viewer engine={engine} plugins={plugins}>
<Stage>
{() => (
<>
<RenderLayer />
<FormLayer />
</>
)}
</Stage>
</Viewer>
);
}Loading live preview…
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { FormLayer, formPlugin, useFormState } from '@embedpdf/react/form';
import { localEngine } from '@embedpdf/engine';
import './basic.css';
const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), formPlugin()];
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()) };
};
function FormToolbar() {
const { fields } = useFormState();
return (
<div className="toolbar">
<output className="readout">{fields.length} fields: click one and fill it in</output>
</div>
);
}
export default function App() {
return (
<Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: forms }]}>
<DocumentGate fallback={<p className="loading">Loading…</p>}>
<FormToolbar />
<Stage className="stage">
{() => (
<>
<RenderLayer />
<FormLayer />
</>
)}
</Stage>
</DocumentGate>
</Viewer>
);
}Each field becomes a real HTML control, placed and styled like the field in the PDF: people type in text boxes, tick checkboxes, pick from lists, and move between fields with Tab. A value is saved into the document as it’s entered, so it’s there when the PDF is downloaded, and every PDF app shows it. The form layer paints the fields as the engine draws them, so while it’s on the page, the render layer leaves them out of the page picture.
Read the form#
useFormState() gives you every field, and re-renders when a value changes:
import { useFormState } from '@embedpdf/react/form';
export function FieldList() {
const { fields } = useFormState();
return (
<ul>
{fields.map((field) => (
<li key={field.name}>
{field.name}: {field.kind}
</li>
))}
</ul>
);
}Each field has its full name (such as billing.name), its kind ('text', 'checkbox',
'radio', 'combobox', 'listbox', 'pushbutton' or 'signature'), its value, and a ref: its
address for everything else. The fields and their values are the engine’s; see
Forms for every kind’s value.
For one field, such as a total you show in your own UI, use useFormValue():
import { toFieldRef, useFormValue } from '@embedpdf/react/form';
export function InvoiceTotal() {
const total = useFormValue(toFieldRef('invoice.total'));
return <output>{total && 'value' in total && total.value}</output>;
}toFieldRef(name) makes a ref from a field’s full name, for when you know a field by name.
Loading live preview…
import { useEffect, useRef, useState } from 'react';
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import {
FormLayer,
formPlugin,
toFieldRef,
useForm,
useFormEvent,
useFormState,
useFormValue,
} from '@embedpdf/react/form';
import type { FormField } from '@embedpdf/react/form';
import { localEngine } from '@embedpdf/engine';
import './read.css';
const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), formPlugin()];
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()) };
};
/** On load: a name filled in. */
function useFilledInName() {
const form = useForm();
const status = useFormState((state) => state.status);
const started = useRef(false);
useEffect(() => {
if (status !== 'ready' || started.current) return;
started.current = true;
void form.setValue(toFieldRef('name'), { value: 'Ada Lovelace' });
}, [form, status]);
}
/** A field's value as text, whatever its kind. */
function valueText(field: FormField): string {
switch (field.kind) {
case 'text':
case 'combobox':
return field.value || '—';
case 'checkbox':
return field.checked ? 'checked' : 'not checked';
case 'radio':
return field.value === 'Off' ? '—' : field.value;
case 'listbox':
return field.selectedValues.join(', ') || '—';
default:
return '';
}
}
function Greeting() {
useFilledInName();
const name = useFormValue(toFieldRef('name'));
const [changed, setChanged] = useState<string | null>(null);
// Every change, whoever made it: typing, a script, or code.
useFormEvent(
(form) => form.onValueChanged,
({ field }) => setChanged(field.name),
);
return (
<div className="toolbar">
<output className="readout">
Hello, {name && 'value' in name && name.value ? name.value : 'stranger'}
</output>
{changed && <output className="note">Last change: {changed}</output>}
</div>
);
}
function FieldList() {
const { fields } = useFormState();
return (
<ul className="fields">
{fields.map((field) => (
<li key={field.name} className="field">
<span className="field-name">
{field.name} <span className="kind">{field.kind}</span>
</span>
<span className="field-value">{valueText(field)}</span>
</li>
))}
</ul>
);
}
export default function App() {
return (
<Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: forms }]}>
<DocumentGate fallback={<p className="loading">Loading…</p>}>
<Greeting />
<div className="viewer">
<Stage className="stage">
{() => (
<>
<RenderLayer />
<FormLayer />
</>
)}
</Stage>
<FieldList />
</div>
</DocumentGate>
</Viewer>
);
}Fill in a field#
setValue() takes the same values a field reads:
await form.setValue(name.ref, { value: 'Ada Lovelace' }); // text
await form.setValue(agree.ref, { checked: true }); // checkbox
await form.setValue(plan.ref, { value: 'yearly' }); // radio group: the button's export value
await form.setValue(country.ref, { value: 'NL' }); // dropdown: an option's value
await form.setValue(toppings.ref, { selectedValues: ['cheese', 'olives'] }); // listIt runs the same checks and scripts as typing does, and resolves with { field, status }: status
is 'applied', 'unchanged', or 'rejected' when the form’s own validation refused the value.
The field shows the new value at once, before the engine answers, and the promise resolves once it has. What the form’s scripts calculate from it goes with it, as one change: one request, and one step to undo. The field stays editable meanwhile; filling it in again is the next change. A value the engine refuses goes back to the one the field had.
To fill many fields at once, such as from your backend, pass them by name:
await form.importValues({ 'billing.name': 'Ada Lovelace', 'billing.country': 'NL', agree: true });importValues() and setValues() write every value as one change, with the calculations run once
after them. Each field’s own keystroke and validation scripts don’t run, as when a script sets a
field’s value in Acrobat.
Loading live preview…
import { useState } from 'react';
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { FormLayer, formPlugin, toFieldRef, useForm } from '@embedpdf/react/form';
import type { FormCapability } from '@embedpdf/react/form';
import { localEngine } from '@embedpdf/engine';
import './fill.css';
const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), formPlugin()];
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()) };
};
/** One field of each kind, with `setValue()` in the shape each one takes. */
async function fillIn(form: FormCapability) {
await form.setValue(toFieldRef('name'), { value: 'Ada Lovelace' }); // text
await form.setValue(toFieldRef('updates'), { checked: true }); // checkbox
await form.setValue(toFieldRef('plan'), { value: 'yearly' }); // radio group: a button's value
await form.setValue(toFieldRef('framework'), { value: 'React' }); // dropdown: an option's value
return form.setValue(toFieldRef('topics'), { selectedValues: ['Forms', 'Signatures'] }); // list
}
function FillToolbar() {
const form = useForm();
const [result, setResult] = useState('');
return (
<div className="toolbar">
<button
type="button"
className="button"
onClick={async () => {
const { status } = await fillIn(form);
setResult(`Filled in: ${status}`);
}}
>
Fill in
</button>
<button
type="button"
className="button"
onClick={async () => {
// Plain values by full name, as your backend would send them.
const { applied, skipped } = await form.importValues({
name: 'Grace Hopper',
framework: 'Vue',
updates: false,
topics: ['Annotations'],
phone: '555-0100',
});
setResult(`${applied.length} filled, ${skipped.length} skipped`);
}}
>
Fill from your backend
</button>
<button
type="button"
className="button"
onClick={async () => {
const { fields } = await form.reset();
setResult(`${fields.length} fields reset`);
}}
>
Reset
</button>
{result && <output className="readout">{result}</output>}
</div>
);
}
export default function App() {
return (
<Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: forms }]}>
<DocumentGate fallback={<p className="loading">Loading…</p>}>
<FillToolbar />
<Stage className="stage">
{() => (
<>
<RenderLayer />
<FormLayer />
</>
)}
</Stage>
</DocumentGate>
</Viewer>
);
}Check required fields#
A form marks some fields as required. Check them before you submit or download:
const { valid, missing } = form.validate();
if (!valid) form.focus(missing[0].ref);missing lists the required fields that are empty, in page order, so you can take the user to the
first one: focus() brings it into view and puts the cursor in it. Only the fields the user may fill
in count: another signer’s are theirs to fill.
Loading live preview…
import { useCallback, useEffect, useRef, useState } from 'react';
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { FormLayer, formPlugin, toFieldRef, useForm, useFormState } from '@embedpdf/react/form';
import type { FormValidation } from '@embedpdf/react/form';
import { localEngine } from '@embedpdf/engine';
import './validate.css';
const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), formPlugin()];
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()) };
};
/** Fill in a name, then check the form, as if it was submitted. */
function useFilledInName(onReady: () => void) {
const form = useForm();
const status = useFormState((state) => state.status);
const started = useRef(false);
useEffect(() => {
if (status !== 'ready' || started.current) return;
started.current = true;
void form.setValue(toFieldRef('name'), { value: 'Ada Lovelace' }).then(onReady);
}, [form, status, onReady]);
}
function SubmitToolbar() {
const form = useForm();
const [check, setCheck] = useState<FormValidation | null>(null);
// Check the required fields.
const validate = useCallback(() => {
const result = form.validate();
setCheck(result);
return result;
}, [form]);
useFilledInName(validate);
// Submit: check, and put the cursor in the first empty field.
const submit = () => {
const first = validate().missing[0];
if (first) form.focus(first.ref);
};
return (
<div className="toolbar">
<button type="button" className="button" onClick={submit}>
Submit
</button>
{check &&
(check.valid ? (
<output className="readout">Every required field is filled in</output>
) : (
<output className="readout missing">
Fill in first: {check.missing.map((field) => field.name).join(', ')}
</output>
))}
</div>
);
}
export default function App() {
return (
<Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: forms }]}>
<DocumentGate fallback={<p className="loading">Loading…</p>}>
<SubmitToolbar />
<Stage className="stage">
{() => (
<>
<RenderLayer />
<FormLayer />
</>
)}
</Stage>
</DocumentGate>
</Viewer>
);
}Move between fields#
Tab and Shift+Tab move through the fields in the document’s order, from page to page, including pages that aren’t on screen: the view follows the field. On each page the fields come in the order the PDF gives: as its tags read (most tagged forms say so), by rows, by columns or as they were added. See Keyboard order. Fields the user can’t fill in are skipped, and a group of radio buttons is one stop, whose buttons the arrow keys move between. Tab on the last field, or Shift+Tab on the first, leaves the form, as it does on a web page.
A signature field is a stop when something can sign it: the signature plugin makes it a button (see “Sign here” in a form), or a control of your own draws it. With neither, the field is only its picture, and the cursor passes over it.
Your code moves the cursor too. focus(ref) brings a field into view, on whatever page it is, and
puts the cursor in it; focusNext() goes on from the field the cursor is in, or was in last:
form.focus(email.ref); // the cursor in a field
form.focus(email.ref, { select: true }); // with its text selected, so typing replaces it
form.focusNext(); // the next field, as Tab does
form.focusNext({ backward: true }); // the one before
form.focusNext({ empty: true, wrap: true }); // the next empty field, starting over at the endBoth return false when there is no such field, none the user can fill in, or none with anything
to put the cursor in. A field takes the cursor as soon as it’s on screen; on iPhone and iPad, the
keyboard opens for a field that was already showing, and one that had to come into view opens it on
a tap.
focusedField is the field the cursor is in, or null, and
onFocusChanged tells you each time it moves, for a help text next to the
form or a step counter.
Calculations, formatting and validation#
Many forms add up totals, format dates and check values with scripts. With JavaScript on in the actions plugin, they run as people type, as in Acrobat:
import { actionsPlugin } from '@embedpdf/react/actions';
import { formPlugin } from '@embedpdf/react/form';
export const plugins = [/* … */ formPlugin(), actionsPlugin({ javascript: { enabled: true } })];When a script refuses a value, such as a date in the wrong format, the field keeps its old value,
the box keeps what was typed so it can be corrected, as in Acrobat, and
onValidationRejected tells you why, so you can show a message.
Loading live preview…
import { useState } from 'react';
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { actionsPlugin } from '@embedpdf/react/actions';
import {
FormLayer,
formPlugin,
toFieldRef,
useFormEvent,
useFormValue,
} from '@embedpdf/react/form';
import { localEngine } from '@embedpdf/engine';
import './scripts.css';
const engine = localEngine();
// The form's scripts run with JavaScript on in the actions plugin.
const plugins = [
stagePlugin(),
renderPlugin(),
interactionPlugin(),
formPlugin(),
actionsPlugin({ javascript: { enabled: true } }),
];
const invoice = async (): Promise<OpenInput> => {
const response = await fetch('https://www.embedpdf.com/pdfs/invoice.pdf');
return { kind: 'bytes', id: 'invoice', bytes: new Uint8Array(await response.arrayBuffer()) };
};
// The amounts and the total are calculated by the form's scripts.
function InvoiceBar() {
const total = useFormValue(toFieldRef('invoice.total'));
const [refused, setRefused] = useState<string | null>(null);
// A script refused a value, such as a date that isn't day/month/year.
useFormEvent(
(form) => form.onValidationRejected,
({ field, issues }) => setRefused(`${field.name}: ${issues[0]?.message ?? 'refused'}`),
);
return (
<div className="toolbar">
<output className="readout">
Total: {total && 'value' in total && total.value ? total.value : 'type a quantity'}
</output>
{refused && <output className="refused">{refused}</output>}
</div>
);
}
export default function App() {
return (
<Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: invoice }]}>
<DocumentGate fallback={<p className="loading">Loading…</p>}>
<InvoiceBar />
<Stage className="stage">
{() => (
<>
<RenderLayer />
<FormLayer />
</>
)}
</Stage>
</DocumentGate>
</Viewer>
);
}The scripts read the form as the user sees it, values still on their way included, so nothing is read from the engine for them. Their engine starts when the first field of a form with scripts takes focus, so the first value doesn’t wait for it; a form without scripts never starts it.
Fields for several people#
When a form goes to several people, each fills in their own fields: a field can be in a group, and a user’s permissions name the groups they fill in. The form layer shows whose field is whose, each group in a color of its own, with nothing to set up.
The PDF holds only each field’s group id. Who a group is belongs to your app, and it changes from one document to the next, so you tell each open document:
form.setGroups([
{ id: 'buyer', label: 'Dana Smith', color: '#2563eb' },
{ id: 'seller', label: 'Lanternfield' }, // a color is picked for it
]);Call it where the document shows, so every document you open gets its own list:
import { useLayoutEffect } from 'react';
import { useForm, type FormGroupInput } from '@embedpdf/react/form';
/** Render it where the document shows, so every document you open gets its own list. */
export function Signers({ signers }: { signers: FormGroupInput[] }) {
const form = useForm();
// Before the first paint, so no field shows in another color first.
useLayoutEffect(() => {
form.setGroups(signers);
}, [form, signers]);
return null;
}- The fields a user may fill in show in their group’s color: a light fill and an edge. Other people’s fields show as the PDF has them, and take no input. So does a field that takes no value any more: a read-only one, or a signature field that’s signed. In design mode every field shows its group’s color.
labelis who the group is, for people. Screen readers read it after the field’s name, “Signature, Dana Smith”, on the user’s own fields and on other people’s.coloris a CSS color, so it can name a variable of yours:color: 'var(--signer-1)'. Without one, a group gets one of eight colors by its place in the list, so the first eight never share one.setGroups()takes the whole list, and an empty one clears it. Call it again when your list changes; the same list again changes nothing. Naming a group needs no permission, so a signer’s page names them too.- Each open document has its own list. The same id can be one person in this document and another in the next.
- A group you don’t name shows too, in one of the eight colors and with no name. A field in no group shows as the PDF has it.
For a legend of your own, groups in the form’s state has every group you named, in your order, then
every other group the form’s fields are in, each as { id, label, color }. A group you didn’t
name has null for its label. form.listGroups() reads the same list once.
Two pages show a group in the same color when they name the same groups in the same order, so give the sender’s page and each signer’s the same list. For a color that never depends on the order, give each group its own.
Names and colors stay in your app, never in the PDF. How strongly the fill shows is
fields.tint, and 0 turns the colors off; see Settings.
Place fields for a signer has a live example.
Reset the form#
await form.reset(); // every field the user may fill in, back to its default
await form.reset([name.ref, email.ref]); // some fieldsMove form data in and out#
For your own backend, plain values are simplest:
const values = form.exportValues(); // { 'billing.name': 'Ada Lovelace', agree: true, … }
await form.importValues(values);Fields are matched by their full name. A field the form doesn’t have, or a value it can’t take, is skipped; the rest still land.
To copy the fields themselves to another document, with their boxes, values and scripts, take
them out as a bundle and import it there. FormTransfer turns a bundle into one JSON text to
store, and back:
const bundle = await form.export(); // every field; or form.export({ fields }), ({ pages })
const text = FormTransfer.stringify(bundle);
const { fields, dropped } = await otherForm.import(await FormTransfer.parse(text));The import adds the fields as one change, and one step to undo: an undo takes them away again.
When your app adds the fields by itself, pass { history: false }, and undo leaves them alone. A
field whose name the form has already is left out and listed in dropped. By default each field
keeps who created and filled it in, which needs canRestoreAttribution(); pass
{ attribution: 'stamp' } to make them yours. See
Import & export.
Loading live preview…
import { useEffect, useRef, useState } from 'react';
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import {
FormLayer,
FormTransfer,
formPlugin,
useForm,
useFormState,
type FormBundle,
} from '@embedpdf/react/form';
import { localEngine } from '@embedpdf/engine';
import './data.css';
const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), formPlugin()];
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()) };
};
/** On load: the form filled in. */
function useFilledIn() {
const form = useForm();
const status = useFormState((state) => state.status);
const started = useRef(false);
useEffect(() => {
if (status !== 'ready' || started.current) return;
started.current = true;
void form.importValues({ name: 'Ada Lovelace', email: 'ada@example.com', framework: 'Svelte' });
}, [form, status]);
}
function DataToolbar() {
useFilledIn();
const form = useForm();
const [bundle, setBundle] = useState<FormBundle | null>(null);
const [result, setResult] = useState('');
return (
<div className="toolbar">
<button
type="button"
className="button"
onClick={async () => {
const exported = await form.export();
// One JSON text: what you'd store, and read back with FormTransfer.parse().
const text = FormTransfer.stringify(exported);
setBundle(exported);
setResult(`Exported ${exported.fields.length} fields, ${text.length} characters of JSON`);
}}
>
Export
</button>
<button
type="button"
className="button"
onClick={async () => {
for (const field of form.list()) await form.delete(field.ref);
setResult('The form is gone');
}}
>
Remove
</button>
<button
type="button"
className="button"
disabled={!bundle}
onClick={async () => {
if (!bundle) return;
const { fields, dropped } = await form.import(bundle);
setResult(`Imported ${fields.length} fields, left out ${dropped.length}`);
}}
>
Import
</button>
{result && <output className="readout">{result}</output>}
</div>
);
}
/** The values as plain data, keyed by full name: what you'd send to your backend. */
function Values() {
const form = useForm();
// The state changes with every value, so this reads them again each time.
useFormState((state) => state.fields);
return <pre className="values">{JSON.stringify(form.exportValues(), null, 2)}</pre>;
}
export default function App() {
return (
<Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: forms }]}>
<DocumentGate fallback={<p className="loading">Loading…</p>}>
<DataToolbar />
<div className="viewer">
<Stage className="stage">
{() => (
<>
<RenderLayer />
<FormLayer />
</>
)}
</Stage>
<Values />
</div>
</DocumentGate>
</Viewer>
);
}Methods#
What useForm() gives you for reading and filling. The verbs that change the form itself are
on Building forms.
| Method | What it does |
|---|---|
get(ref) | One field, with its value, or null when the form has no such field. Read the form |
getValue(ref) | One field’s value, in the shape setValue() takes, or null. In a component, use useFormValue(ref). |
getFieldForWidget(widget) | The field a box belongs to, from the box’s ref |
getWidget(widget) | A box’s row: its page, its place (rect), its look and its state, or null when no page shows it |
getWidgets(ref) | Every box a field shows in, as rows in the field’s order: a radio group’s buttons, or a field repeated on several pages |
listGroups() | Every group setGroups() named, then every other group the form’s fields are in, as { id, label, color }. Fields for several people |
setGroups(groups) | Says who this document’s groups are, { id, label, color } each: the whole list, and [] clears it. Fires onGroupsChanged. Fields for several people |
listWidgets(page) | Each field box on a page, with its place (box, rotation and rect), its control, its value and whether it can be filled. For drawing the fields yourself; see What a box tells you and Turned fields. |
getWidgetAt(page, point) | The field box under a point on a page, with its field and its place (box, rotation and rect), or null |
setValue(ref, value) | Fills in a field with { value }, { checked } or { selectedValues }, running the form’s checks and scripts. Resolves { field, status }. Fill in a field |
setValues(entries) | Fills in several fields, each { ref, value }, as one change with one recalculation; a field you may not fill in, or a value it can’t take, fails on its own. Resolves { applied, skipped, failed }. |
importValues(values) | Fills in fields by full name from a plain object, as one change with one recalculation. Resolves { applied, skipped, failed }. Move form data in and out |
exportValues() | Every value, keyed by full name, as a plain object |
export(selection?) | Whole fields with their boxes, values and scripts, as a bundle: every field, or { fields } or { pages }. Move form data in and out |
import(bundle, options?) | Adds a bundle’s fields, as one change and one step to undo. Resolves { fields, refMap, dropped }. Needs canDesign(). Move form data in and out |
reset(refs?) | Puts back each field’s default, for every field the user may fill in or the fields you pass. Resolves { fields }, the fields it changed. Reset the form |
validate() | Checks the required fields the user may fill in. Returns { valid, missing }, the empty ones in page order. Check required fields |
focus(ref, options?) | Brings a field into view and puts the cursor in it; { select: true } selects its text. Returns false for a field the user can’t fill in. Move between fields |
focusNext(options?) | Moves the cursor to the next field, as Tab does: { backward, empty, wrap }. Returns false when there’s none. Move between fields |
getFocusedField() | The field the cursor is in, or null |
activateWidget(widget) | Does what a click on a field box does, such as running a button’s action |
getSnapshot() | Everything at once, as the user sees it: what the engine’s list() returns, with the values still on their way. fields, widgets, formKind, needsAppearances and calculationOrder |
refresh() | Reads the whole form again, and onResynced fires. You rarely need it: the plugin follows every change, whoever made it. |
canRead(), canFill(ref) | Whether reading the form, and filling in a field, are allowed. Permissions |
getSettings(), updateSettings(changes), resetSettings() | Reads the settings, changes them while the app runs, or goes back to what you registered. In a component, use useFormSettings(). Settings |
Every method that returns a promise also takes a signal in its options, to cancel it.
State#
Everything useFormState() gives you. Your component re-renders when a value changes. The method in the last column reads the same value once.
| Field | What it is | Read once |
|---|---|---|
fields | Every field, with its value | list(), or list({ kind, page, name }) for some |
status | Whether the form is read: 'idle', 'loading', 'ready', 'forbidden' or 'error' | getStatus() |
formKind | What the document has: 'none', 'acroform' (a regular PDF form) or 'xfa' | getFormKind() |
selectedField | In design mode, the field whose boxes are selected (one, or several of the same field), or null; see Building forms | getSelectedField() |
focusedField | The field the cursor is in, or null; see Move between fields | getFocusedField() |
selectedFields | In design mode, every field with a selected box; see Building forms | listSelectedFields() |
groups | Every group you named or the form’s fields are in, as { id, label, color }; see Fields for several people | listGroups() |
designGroup | In design mode, the group that fields placed with a tool go in, or null for none; see Building forms | getDesignGroup() |
For one field, useFormValue(ref) re-renders only when that field’s value changes.
Settings#
Set them when you register the plugin, and change them while the app runs with
form.updateSettings({ … }); form.resetSettings() goes back to what you registered, and
useFormSettings() gives you the current settings.
| Setting | What it does | Default | From CSS |
|---|---|---|---|
validation | Run the form’s own checks ('scripts'), or accept every value ('none') | 'scripts' | — |
focus.color | The ring around the field being filled in | the viewer’s accent | --epdf-form-focus |
fields.border | The edge of a field that has no border of its own | the viewer’s accent at 55% | --epdf-form-field-border |
fields.background | Inside a field that has no background of its own | 'rgb(255 255 255 / 0.92)' | --epdf-form-field-background |
fields.color | The check mark and text of a field that has no color of its own | '#1f2a44' | --epdf-form-field-color |
fillable | Which fields people fill in by hand: true, false, or field kinds | true | — |
fields.tint | How strongly a field shows its group’s color, from 0, not at all, to 1 | 0.16 | --epdf-form-field-tint |
Scripts need JavaScript on in the actions plugin; without it, 'scripts' accepts every value too,
and a form with scripts logs a hint once.
fillable is for the people using your app. A field it leaves out draws as a read-only field
does, and takes no typing, clicks or picks; your code still fills it in with setValue() and
importValues(), and canFill(ref) doesn’t change:
formPlugin({ fillable: false }); // show the values, take no input
form.updateSettings({ fillable: ['text', 'checkbox'] }); // only these kinds
form.updateSettings({ fillable: true }); // every field againThe kinds are 'text', 'checkbox', 'radio', 'combobox', 'listbox', 'pushbutton' and
'signature' (signing a field is filling it in). To stop your code too, leave doc.forms.fill out
of the scope (see Permissions).
The colors are what the viewer draws around fields; a field’s own colors are saved in the PDF (see Building forms). A CSS variable wins over the setting: see Colors & theming.
Loading live preview…
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { FormLayer, formPlugin, useForm, useFormSettings } from '@embedpdf/react/form';
import { localEngine } from '@embedpdf/engine';
import './colors.css';
const engine = localEngine();
// The colors the viewer draws around fields; `null` follows the viewer's accent.
const plugins = [
stagePlugin(),
renderPlugin(),
interactionPlugin(),
formPlugin({ fields: { border: '#ea580c' } }),
];
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()) };
};
const COLORS = [
['Accent', null],
['Orange', '#ea580c'],
['Green', '#16a34a'],
] as const;
function ColorToolbar() {
const form = useForm();
const settings = useFormSettings();
return (
<div className="toolbar">
<span className="label">Edges</span>
<div className="segments">
{COLORS.map(([label, color]) => (
<button
key={label}
type="button"
className="segment"
aria-pressed={settings.fields.border === color}
onClick={() => form.updateSettings({ fields: { border: color } })}
>
{label}
</button>
))}
</div>
<span className="label">Focus</span>
<div className="segments">
{COLORS.map(([label, color]) => (
<button
key={label}
type="button"
className="segment"
aria-pressed={settings.focus.color === color}
onClick={() => form.updateSettings({ focus: { color } })}
>
{label}
</button>
))}
</div>
</div>
);
}
export default function App() {
return (
<Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: forms }]}>
<DocumentGate fallback={<p className="loading">Loading…</p>}>
<ColorToolbar />
<Stage className="stage">
{() => (
<>
<RenderLayer />
<FormLayer />
</>
)}
</Stage>
</DocumentGate>
</Viewer>
);
}Events#
import { useFormEvent } from '@embedpdf/react/form';
import { autosave } from './api';
export function Autosave() {
useFormEvent(
(form) => form.onValueChanged,
({ field }) => autosave(field.name),
);
return null;
}| Event | Fires when | Carries |
|---|---|---|
onValueChanged | A field’s value changed | field, origin |
onValidationRejected | The form’s validation refused a value | field, issues |
onFocusChanged | The cursor moved into a field, to another one, or out of the fields | field, widget |
onResynced | The whole form was read, as when it opens, after refresh() or a repair | snapshot |
onGroupsChanged | setGroups() changed who the document’s groups are | groups |
onSettingsChanged | The settings changed | settings, changedKeys |
Fields that are added, changed or removed have their own events; see Building forms.
Permissions#
| Permission | What it allows | Check |
|---|---|---|
doc.forms.read | Reading the form | form.canRead() |
doc.forms.fill | Filling it in | form.canFill(ref) |
Without it, the fields show their values but can’t be changed. A user with a fields:fill
permission for one group fills in that group’s fields only: form.canFill(ref) answers per field,
the other fields can’t be changed and Tab skips them, validate() leaves them out, and reset()
leaves them as they are. See Signers and groups.
Good to know#
Forms and annotations#
A field’s widgets are the form’s: the annotation plugin never lists them. With the
annotation plugin registered, the <FormLayer> and the annotation layer share the page: fields stay fillable with the
pointer tool, and become movable boxes in design mode.
Keyboard#
Tab and Shift+Tab move between fields in the document’s order (see Move between fields), and the arrow keys between the buttons of a radio group. In a text box, Enter confirms and Escape puts back the value it had.
Screen readers#
Each control is named by the field’s tooltip (its alternateName), or by its name when it has
none. A radio button adds the option it stands for, its export value, the way screen readers read
one in Acrobat: Plan: monthly. It also says where it comes in its group (1 of 2, in the order
the arrow keys go round), since a group’s buttons stand apart on the page. A field of a
group you named says whose it is last: Plan: monthly, Dana Smith.
When you draw the fields
yourself, each entry of listWidgets(page) carries the name as label, and a radio button its
place as inGroup, { position, size }, for aria-posinset and aria-setsize.
Turned fields#
A field can be turned a quarter turn: so that it reads upright on a page that is shown turned, such
as a scan saved sideways, or so that a label runs up the side of a page. <FormLayer> places each
control in the field’s frame and turns it with the field, so people type, tick and pick in the
direction the field reads. A dropdown’s open list is the browser’s own, and opens unturned.
When you draw the fields yourself, each entry of listWidgets(page) says where it is with three
values:
| Value | What it is |
|---|---|
box | The frame the field’s contents are laid out in, before the turn |
rotation | The turn, clockwise about the middle of box: 0, 90, 180 or 270 |
rect | Where the field stands on the page: box turned |
Place your control at box and turn it by rotation about its middle: it then covers rect. For
a field that isn’t turned, box and rect are the same and rotation is 0.
Collecting responses#
On the local engine, the values live in the document in this tab until it’s downloaded.
XFA forms#
Some PDFs also carry a form in the older XFA format. The viewer works with the document’s regular fields and never runs XFA; see Forms.
Signed documents#
A signature can lock the whole form, or some fields. Locked fields show their values and can’t be changed; see Signatures.
Your feedback goes directly to the documentation team.