--- title: Creating form fields description: Add text fields, checkboxes, radio groups, dropdowns, lists, buttons and signature fields to a PDF, change or delete them, and repair a broken form. --- {/* Generated from docs/content — edit there, then `pnpm docs:sync`. */} # Creating form fields `create()` adds a field to the document and places it on a page, in one call: ```ts const { field } = await doc.forms.create({ kind: 'text', name: 'customer.email', maxLength: 60, widgets: [{ page: page.ref, rect: { x: 72, y: 168, width: 228, height: 24 } }], }); await doc.forms.setValue(field.ref, { value: 'ada@example.com' }); ``` The new field fills in, exports and shows like any other field; see [Reading & filling forms](/docs/engine/forms). ## Fields and widgets A form has two parts. The **field** holds the value: it has a name, a kind and a few settings, and it belongs to the document, not to a page. A **widget** is where the field shows: the box on a page that you see and click. A widget is an annotation of kind `'widget'`, but it's the form's: `doc.forms.list()` lists it in `widgets`, and you place, move and style it through the form. Most fields have one widget. A radio group has one per button, and a field can have widgets on several pages that all show the same value. ## Create a field `create()` takes the kind, the field's full name and its settings. `widgets` places it on the pages, one entry per place it shows; leave it out to create a field that isn't on any page yet, and [add a widget](#add-a-widget) later. | Field | What it is | Default | | :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------- | | `kind` | `'text'`, `'checkbox'`, `'radio'`, `'combobox'`, `'listbox'`, `'pushbutton'` or `'signature'` | | | `name` | The full name. Dots make groups: `customer.email` creates `customer` if it's new. | | | `widgets` | Where it shows: a list of `{ page, rect }`, `rect` in points from the page's top-left, each with the [widget's look](#the-widgets-look). | not placed | | `readOnly` | PDF apps don't let the user change it. | `false` | | `required` | PDF apps ask for a value before the form is submitted. | `false` | | `noExport` | Left out when the form is submitted. | `false` | | `alternateName` | The tooltip PDF apps show, also read by screen readers. | none | | `mappingName` | A second name, for other apps that export the form's data. | none | | `groupId` | The group it goes in, the shorthand for `assignment`. Another group than your own takes `fields:set-group` for it (see [Signers and groups](/docs/engine/forms/groups)). | no group | | `purpose` | What its value means, such as `'email'`; see [Purpose](#purpose). | none | | `placeholder` | The author's text to show while the field is empty, such as `'name@example.com'`: kept with the field, never its value, and the same 1 to 256 characters a [purpose](#purpose) takes. | none | | `assignment` | Who fills it in: a group, anyone (which takes `fields:set-group:all`), or no one in particular. Not with `groupId` (see [Who fills a field in](/docs/engine/forms/groups#who-fills-a-field-in)). | unassigned | `create()` is one change: when any part of the draft is invalid, it fails with `InvalidArg` (or `NotFound` for a page that isn't there) and creates nothing. A name that's already taken fails with `InvalidArg` too. Each kind adds its own settings: | Family | Settings | | :----------- | :------------------------------------------------------------------------------------------------------------------------------- | | `text` | `defaultValue`, `maxLength`, `multiline`, `password`, `comb` (one character per box, with `maxLength`), `format` | | `checkbox` | Each widget's `exportValue`: what the form data holds when it's checked. Default `'Yes'`. | | `radio` | Each widget's `exportValue` (one widget per button), `noToggleToOff`, `radiosInUnison` | | `combobox` | `options`, `defaultValue`, `edit` (the user may also type their own text), `format` | | `listbox` | `options`, `multiSelect`, `defaultValue` (option values; more than one needs `multiSelect`) | | `pushbutton` | Only widgets, each with its `caption` and `layout`. See [A push button](#a-push-button). | | `signature` | Only widgets, each drawn as its box until a mark is in it. Signing it is on [Digital signatures](/docs/engine/forms/signatures). | `format` makes a text field or a dropdown a date or a time field; see [Dates and times](#dates-and-times). ### A radio group A radio group has one widget per button. Each button's `exportValue` is the value you choose it with, so it can't be `'Off'`: ```ts const { field } = await doc.forms.create({ kind: 'radio', name: 'plan', noToggleToOff: true, 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' }, ], }); await doc.forms.setValue(field.ref, { value: 'monthly' }); ``` ### A dropdown Options are `{ label, value }`: the user sees the `label`, the form stores the `value`. ```ts await doc.forms.create({ kind: 'combobox', name: 'country', options: [ { label: 'Netherlands', value: 'NL' }, { label: 'Belgium', value: 'BE' }, ], defaultValue: 'NL', widgets: [{ page: page.ref, rect: { x: 72, y: 252, width: 148, height: 20 } }], }); ``` ### A push button A push button holds no value: it does something when it's clicked. Give each widget its `caption` and what a click does, in `actions` (see [Widget actions](#widget-actions)): ```ts await doc.forms.create({ kind: 'pushbutton', name: 'clear', widgets: [ { page: page.ref, rect: { x: 400, y: 700, width: 120, height: 28 }, caption: 'Clear form', interiorColor: '#f6f8fa', actions: { activate: { type: 'reset-form', fields: null, exclude: false } }, }, ], }); ``` The engine draws the button: its background, its border, and the caption centred in the widget's font. `setValue()` refuses a push button with `InvalidArg`. A button that only goes to a page, resets the form or shows and hides fields needs `doc.forms.modify` alone; one that runs a script, submits the form or opens a web address needs `doc.forms.script` too. ### A button with an image A push button can show an image: someone's initials, a second signature, a photo. One that a person fills with a picture is an image field, as Acrobat calls it. Create it with `takesImage: true`, give its widget the layout `'image'`, then put the image in with `setButtonImage()`: ```ts const { field } = await doc.forms.create({ kind: 'pushbutton', name: 'initials_page_1', required: true, takesImage: true, widgets: [{ page: page.ref, rect: { x: 480, y: 740, width: 72, height: 36 }, layout: 'image' }], }); field.takesImage; // true const { field: filled } = await doc.forms.setButtonImage(field.ref, png); filled.hasImage; // true await doc.forms.setButtonImage(field.ref, null); // take it out ``` The image is a PNG, a JPEG or a one-page PDF, as a `Uint8Array` or a `Blob`: what a [stamp](/docs/engine/annotations/stamps) takes. `null` takes the image out, and the button shows its box again. The image is one part of the button's look, which is drawn from the image, the caption and the layout. - **Every widget of the field shows it.** A field with a widget on each of three pages shows the same image three times, and the file holds the image once. A widget you [add later](#add-a-widget) gets it too. - **It fits inside the border,** whole and in the middle, as Acrobat fits one. - **Where it shows** is each widget's `layout`: | `layout` | The widget shows | | :---------------- | :------------------------------------ | | `'caption'` | Its caption alone. The default. | | `'image'` | Its image alone | | `'caption-below'` | Its caption below the image | | `'caption-above'` | Its caption above the image | | `'caption-right'` | Its caption to the right of the image | | `'caption-left'` | Its caption to the left of the image | | `'caption-over'` | Its caption over the image | `setButtonImage()` leaves the layout as it is. On a widget whose layout is `'caption'` the image is kept and not shown, as in Acrobat. - **`hasImage`** says whether the field holds an image: `true` when one of its widgets has one. - **It is filling in, not design.** `setButtonImage()` needs the right to fill the field in, as `setValue()` does: `doc.forms.fill`, or `fields:fill` for the field's group (see [Signers and groups](/docs/engine/forms/groups)). On a field a signature locked it fails with `ProtectedDocument`, and on any other kind of field with `InvalidArg`. A signature that allows filling in stays valid after it, in the engine's [analysis](/docs/engine/forms/signatures#how-changes-are-judged) and in Acrobat. - **One undo** puts back the image the field had before, or none. - **Other PDF apps see the image.** It is each widget's icon (`/MK /I`), and the engine draws the widget's look from it, as Acrobat writes one. A button made in Acrobat with an icon reads with its layout and `hasImage: true`. It resolves what `update()` resolves: the field as it is now, `widgets`, the rows of its widgets, and `meta`. #### An image field A PDF has no image field of its own. Acrobat's is a push button whose press runs one script, `event.target.buttonImportIcon()`, which asks for a picture and puts it in the button. That script is what makes a button an image field, and `takesImage` is how the engine reads and writes it: ```ts field.takesImage; // true: every widget's press is that script await doc.forms.update(field.ref, { takesImage: false }); // a button again await doc.forms.update(field.ref, { takesImage: true }); // and an image field ``` - **Reading.** `takesImage` is `true` when the button has a widget and every widget's press runs that script and nothing else, as its `activate` action or on `mouseUp`. Anything else is `false`: no script, another script, the script with more after it, or a widget without it. So a button that only shows an image, such as a logo, is no image field, and neither is one that submits the form. Its other events (`focus`, `cursorEnter` and so on) don't count either way. - **Writing.** `takesImage: true` in `create()` or `update()` writes the script as each widget's `activate` action, as Acrobat writes it, so a click on the field in Acrobat asks for a picture. `takesImage: false` takes the script off each widget whose press is exactly it, and leaves any other action alone. A field that already is what you ask for is left as it is. - **A widget you [add later](#add-a-widget)** to an image field gets the script too. - **Permission.** It needs `doc.forms.modify` alone, not `doc.forms.script`: the engine writes one fixed script, as it does for a [format](#dates-and-times). - **It never overwrites an action.** `takesImage: true` fails with `InvalidArg` when a widget's press already runs another action: remove that action first, with [`updateWidget()`](#widget-actions). It also fails when the button has no widget, when the same `create()` names an `activate` or `mouseUp` action for a widget, and on any other kind of field. - **The image is its own fact.** `takesImage` says the field is one a person fills with a picture, and `hasImage` that it holds one now. Setting either leaves the other as it is, and `setButtonImage()` puts an image in any push button. - **It travels with the field.** A [copy](#copy-a-field) and an [import](import-export#copy-the-design) of an image field make an image field, without `doc.forms.script` too. ### The widget's look Next to `page` and `rect`, each entry of `widgets` takes the widget's style. These are the same fields you change later with `doc.forms.updateWidget()`: | Field | What it is | | :-------------- | :----------------------------------------------------------------------------------------------------------- | | `color` | Border color, `'#rrggbb'` | | `interiorColor` | Background color | | `strokeWidth` | Border width in points | | `borderStyle` | `'solid'`, `'dashed'`, `'beveled'`, `'inset'` or `'underline'` (a line under the field) | | `dashArray` | A dashed border's dash and gap lengths in points, such as `[3, 2]` | | `fontFamily` | The `name` of a font in `doc.fonts.list()`, such as `'helvetica'`; see [Fonts](/docs/engine/documents/fonts) | | `fontSize` | Text size in points | | `fontColor` | Text color | | `textAlign` | `'left'`, `'center'` or `'right'` | | `caption` | A push button's caption; other widgets take none | | `layout` | Where a push button shows its caption and its image; see [A button with an image](#a-button-with-an-image) | | `checkStyle` | A checkbox's or radio button's mark; other widgets take none | ```ts widgets: [ { page: page.ref, rect: { x: 72, y: 208, width: 228, height: 24 }, color: '#1f6feb', interiorColor: '#f6f8fa', fontSize: 10, }, ], ``` A mark is `'check'`, `'cross'`, `'star'`, `'circle'`, `'square'` or `'diamond'`. With `checkStyle: null`, a checkbox draws a check and a radio button a circle. A font the document already has reads as its name in `doc.fonts.list()`, such as `'Roboto-Bold'`. Changing a widget's color or size keeps its font, whatever it is; to change the font, name one whose `canChoose` is `true`. Text in any language is filled in: characters the widget's font doesn't have come from fallback fonts (see [Text in any language](/docs/engine/documents/fonts#text-in-any-language)). To change the look later, update the widget with the same fields (see [Move and style widgets](#move-and-style-widgets)). An entry also takes what the widget does when it's clicked, in `actions` (see [Widget actions](#widget-actions)), and a quarter turn of its contents, in `rotation` (see [Turned widgets](#turned-widgets)). ## Change a field `update()` takes the field's `ref` and only the settings you want to change: ```ts await doc.forms.update(field.ref, { required: true, maxLength: 80 }); ``` A setting you leave out keeps its value. `null` removes one: `{ maxLength: null }` for no limit, `{ defaultValue: null }` for no default, `{ alternateName: null }` for no tooltip, `{ groupId: null }` for no group, `{ purpose: null }` for no purpose, `{ placeholder: null }` for no placeholder, `{ format: null }` for no format. `{ assignment: { kind: 'unassigned' } }` leaves a field to no one in particular, from any assignment: see [Who fills a field in](/docs/engine/forms/groups#who-fills-a-field-in). You can change the settings in the tables above, except the kind and the widgets. A signature field takes the settings every field has: `name`, `readOnly`, `required`, `noExport`, `alternateName`, `mappingName`, `groupId`, `purpose` and `placeholder`. Also: - `name` renames the last part of the name: `customer.email` renamed to `'contact'` becomes `customer.contact`. A name with dots, or one a sibling already has, fails with `InvalidArg`. A field can't move to another group. - `options` replaces the whole list of a dropdown or list. - `maxLength` fails with `InvalidArg` when the current text is longer. ## Purpose A field's `purpose` says what its value means: an email address, the signer's name, the day they signed. The kind says how the value is stored; the purpose says what it is for: ```ts const { field } = await doc.forms.create({ kind: 'text', name: 'buyer.email', purpose: 'email', }); field.purpose; // 'email' await doc.forms.update(field.ref, { purpose: null }); // none ``` The engine stores the purpose with the field and hands it back on every read. It reads nothing into it: a purpose changes nothing about how a field fills in, shows or exports. What a purpose does is up to your app, or to the viewer. Any string is a purpose. These are the well-known ones. Use them for these meanings, so that every app reading the file agrees: | Purpose | The value is | | :------------------- | :---------------------------- | | `name` | The person's full name | | `email` | Their email address | | `organization` | Their company or organization | | `organization-title` | Their job title | | `signature` | Their signature | | `initials` | Their initials | | `date-signed` | The day they signed | The first four are the web's own names for these values, the ones HTML's `autocomplete` takes. - **What it takes.** 1 to 256 characters, with no space at the start or the end and no NUL character (`\u0000`). Anything else fails with `InvalidArg`. - **None.** Left out or `null`, a field has no purpose, and reads `purpose: null`. - **Every kind of field has one.** A signature field and a push button too. - **Permission.** Setting it needs `doc.forms.modify`, like any setting. Whoever may read the form reads it. - **In the file.** It is kept in the field's own private entry, beside its group. Other PDF apps don't read it. - **Copies.** A [copy](#copy-a-field) and an [import](import-export) keep it. ## Dates and times A text field or a dropdown can have a `format`: the shape its value has. A date field is a text field with a date format: ```ts const { field } = await doc.forms.create({ kind: 'text', name: 'delivery.date', format: { kind: 'date', pattern: 'dd/mm/yyyy' }, }); field.format; // { kind: 'date', pattern: 'dd/mm/yyyy' } ``` In the file, a format is the field's format script and its keystroke script, as Acrobat writes them. So Acrobat offers its date picker on a date field made here, and a date field made in Acrobat reads as one here. ### Read a format A field's `format` is one of four, by its format script: - **`{ kind: 'date', pattern }`:** the script is `AFDate_FormatEx("pattern")`, or the older `AFDate_Format(n)`. - **`{ kind: 'time', pattern }`:** it is `AFTime_FormatEx("pattern")`, or the older `AFTime_Format(n)`. - **`{ kind: 'other' }`:** any other format script: a number, a percentage, code of its own. - **`null`:** the field has no format script. How the engine tells them apart: - **The format script decides,** as it does in Acrobat. A keystroke script on its own is no format, and neither is a name that ends in `_af_date`. - **The script is that one call and nothing else.** Spaces around it and a `;` after it are fine. Code that only contains the call reads as `'other'`. - **An older call names its pattern by number.** `AFDate_Format(2)` is `mm/dd/yy`, and `pattern` is the pattern the number stands for. A number Acrobat's list doesn't have reads as `'other'`. - **A pattern the engine doesn't take** (see [Patterns](#patterns)) reads as `'other'`. So does a pattern of the other kind: `AFDate_FormatEx("HH:MM")` is a date call with a time alone, and `AFTime_FormatEx("dd/mm/yyyy")` a time call with a date. - **A kind your version doesn't know reads as `'other'` too.** A later version can add kinds, such as a number. - **Other kinds of field have no `format`.** Only a text field and a dropdown carry the key. - **Permission.** Whoever may read the form reads it: `doc.forms.read`. ### Patterns A pattern is made of these groups of letters. The examples show 5 March 2026, at 14:07:09: | Letters | What they show | | :----------------------- | :----------------------------------- | | `yyyy`, `yy` | The year: `2026`, `26` | | `mmmm`, `mmm`, `mm`, `m` | The month: `March`, `Mar`, `03`, `3` | | `dd`, `d` | The day: `05`, `5` | | `HH`, `H` | The hour, out of 24: `14`, `14` | | `hh`, `h` | The hour, out of 12: `02`, `2` | | `MM` | The minute: `07` | | `ss` | The second: `09` | | `tt` | `am` or `pm` | Capitals matter: `mm` is the month and `MM` the minute. A pattern is at most 64 characters, and each kind of format has its own: - **A date's pattern has a date in it,** and may carry a time: `dd/mm/yyyy`, `mmm d, yyyy`, `m/d/yy HH:MM`. A time on its own is no date pattern. - **A time's pattern is a time and nothing else:** `HH:MM`, `h:MM tt`, `hh:MM:ss tt`. With a date in it, or anything else around the time, it is no time pattern. These rules keep a pattern to what a field can show and then read back: - **Between a date's groups** go spaces and `/`, `-`, `.` and `,`. - **A time is written with colons, once:** the hour, then `:MM`, then `:ss` for seconds, then `tt` for am or pm. `h:MM tt`, `HH:MM:ss` and `hh:MMtt` are times. `HH.MM`, minutes on their own and `tt h:MM` are not. - **Two numbers never touch.** `yyyymmdd` is no pattern: its digits would read back as one number. A month's name between them is enough, as in `dmmmyy`. - **The year, the month and the day each go in once at most.** `yyyy/mm/mm/dd` is no pattern: read back, the month's second copy would be taken for the day. A month by its name and by its number is the month twice. - **Nothing else.** Another letter (`dddd` for a weekday), a quote or words of your own make it a pattern the engine doesn't take. The rules are there because a field has to take back what it shows. The script that checks what a person types reads numbers and a time this way, and a time field's script reads a time and no date. A pattern outside the rules would show text its own field then refuses. `isDatePattern()` and `isTimePattern()` say whether a string is a pattern of the kind, before you write it. `STANDARD_DATE_PATTERNS` and `STANDARD_TIME_PATTERNS` are the patterns Acrobat's older calls name by number, in its order: 14 for a date, from `m/d` to `m/d/yy HH:MM`, and 4 for a time. All four come from the engine package. ### Set a format `create()` and `update()` take `format` on a text field and a dropdown: ```ts await doc.forms.update(field.ref, { format: { kind: 'time', pattern: 'HH:MM' }, }); // No format await doc.forms.update(field.ref, { format: null }); ``` - **A date writes both scripts:** `AFDate_FormatEx("dd/mm/yyyy");` as the format script and `AFDate_KeystrokeEx("dd/mm/yyyy");` as the keystroke script. - **A time writes `AFTime_FormatEx("h:MM tt");` and `AFTime_Keystroke(1);`.** Acrobat has no keystroke call that takes a time's pattern, only one that names one of its four time patterns by number. The engine names the one with the same shape: with or without seconds, on a 12 or a 24 hour clock. - **It replaces the two scripts the field had,** whoever wrote them. - **`null` removes both,** also from a field whose format is `'other'`. On a field with no format it changes nothing: a keystroke script on its own stays. - **The format the field already has changes nothing.** Its scripts stay as they are, an older `AFDate_Format(2)` too. - **`{ kind: 'other' }` can't be written.** Write such a format as scripts, in [`actions`](#scripts-and-calculations). - **A pattern that is none of the format's kind** fails with `InvalidArg`: a time alone as a date, a date as a time, or a pattern outside the [rules](#patterns). So does a `format` on another kind of field. Nothing is written. - **`format` and a script for the same event don't go together.** A call that names `format` and `actions.format` or `actions.keystroke` fails with `InvalidArg`. - **Permission.** `format` needs `doc.forms.modify` alone, not `doc.forms.script`. The engine writes the two scripts itself, from a pattern it checked, so no code of yours goes into the document. The two scripts also read back in `field.actions`, as any script does. Changing or removing one there changes what `format` reads. Undoing a format puts back the scripts the field had before, a number format's too. After a later change to the field, two cases leave the field as it is, as they do for any script: someone wrote one of its scripts since, or the format replaced actions a script can't make again, such as a script that goes on to a GoTo. See [When the document changed since](/docs/engine/documents/changes#when-the-document-changed-since). A [copy](#copy-a-field) and an [import](import-export) keep a date or a time format, without `doc.forms.script` too. ### Write and read a date yourself The engine doesn't check a value against the format: `setValue()` stores the text you give it (see [Calculations, formatting and validation](/docs/engine/forms#calculations-formatting-and-validation)). `formatDate()` writes a date as a pattern shows it, and `parseDate()` reads one back. They come from `@embedpdf/core-acrojs`, the package that runs a form's scripts in the viewer, and run no script themselves: ```ts import { formatDate, parseDate } from '@embedpdf/core-acrojs'; const today = { year: 2026, month: 11, day: 24 }; const afternoon = { ...today, hour: 14, minute: 7 }; formatDate(today, 'dd/mm/yyyy'); // '24/11/2026' formatDate(today, 'mmm d, yyyy'); // 'Nov 24, 2026' formatDate(afternoon, 'h:MM tt'); // '2:07 pm' parseDate('05/03/2026', 'dd/mm/yyyy', today); // { year: 2026, month: 3, day: 5, // hour: 0, minute: 0, second: 0 } parseDate('soon', 'dd/mm/yyyy', today); // null ``` A date is its parts, as the field shows them, with no time zone: `month` is 1 to 12, and the time of day is midnight when you leave it out. - **`formatDate(date, pattern)`** gives the text the field's own format script writes for that date, since both run the same code. - **`parseDate(text, pattern, today)`** reads what the field's keystroke script accepts: it takes `5/3/26` under `dd/mm/yyyy`, and a month by its name. Text that is no date, or a day the month doesn't have, gives `null`. - **`today` is required,** as its year, month and day: neither function reads a clock. It fills in what the text leaves out, so under `d/m`, `5/3` is 5 March of today's year. - **Text the pattern can't read gives `null`,** an ISO date under `dd/mm/yyyy` too. A format script tries JavaScript's own date reading for such text, which differs from one browser to the next; `parseDate()` doesn't. - **Every pattern the engine takes reads back:** `parseDate()` of what `formatDate()` wrote gives the same date, on the parts the pattern shows. ## Scripts and calculations A field can run scripts: while the user types (`keystroke`), to show the value (`format`), to check it (`validate`) and to work it out from other fields (`calculate`). `create()` and `update()` take them in `actions`: ```ts const { field: total } = await doc.forms.create({ kind: 'text', name: 'total', readOnly: true, actions: { calculate: { type: 'javascript', script: 'event.value = this.getField("subtotal").value * 1.21;', }, format: { type: 'javascript', script: 'AFNumber_Format(2, 0, 0, 0, "€ ", true);' }, }, }); await doc.forms.update(total.ref, { actions: { format: null } }); // remove one script ``` A script sets that event's, `null` removes it, and an event you leave out keeps its script. A field's events take JavaScript only: any other action fails with `InvalidArg`. A script can name more scripts to run after it, in `next`. For a date or a time you write no script: set the field's [`format`](#dates-and-times), which needs no `doc.forms.script`. The engine stores the scripts; it doesn't run them. The viewer's form plugin runs them while the user fills the form in (see [Calculations, formatting and validation](/docs/engine/forms#calculations-formatting-and-validation)). ### The calculation order Calculate scripts run in the form's calculation order, which `doc.forms.list()` returns as `calculationOrder`. A field joins it at the end when it gets a calculate script, and leaves it when the script is removed or the field is deleted. `reorderCalculations()` moves fields in it, the way `reorderWidgets()` restacks widgets: ```ts const { calculationOrder } = await doc.forms.reorderCalculations([tax.ref], { before: total.ref }); ``` A field must be in the order to move it (`NotFound` otherwise). A result of `create()`, `update()` or `delete()` that changed the order carries the new one as `calculationOrder`. ## Delete a field `delete()` removes the field and all of its widgets from their pages: ```ts await doc.forms.delete(field.ref); ``` ## Add a widget To show a field in one more place, give `addWidget()` the place, the same shape as an entry of `widgets` in `create()`: ```ts const { field: updated } = await doc.forms.addWidget(field.ref, { page: page.ref, rect: { x: 300, y: 112, width: 150, height: 20 }, }); ``` The field now shows in both places, with the same value. For a radio group, pass the new button's `exportValue` in the same object; a checkbox widget gets `'Yes'` when you leave it out. A push button that holds an [image](#a-button-with-an-image) puts it in the new place too, as a text field shows its value there. Where it shows is the new place's own `layout`, which you give here: without one the place shows its caption alone and keeps the image without showing it. The new place of an [image field](#an-image-field) gets its press script too, so the field stays one, unless you give the place an `activate` or `mouseUp` action of its own. For a second place of the same initials: ```ts await doc.forms.addWidget(initials.ref, { page: lastPage.ref, rect: { x: 480, y: 740, width: 72, height: 36 }, layout: 'image', }); ``` ## Copy a field `copy()` makes a new field from each field you name, with all of its widgets, as `doc.annotations.copy()` does for annotations: ```ts const { fields } = await doc.forms.copy([field.ref], { page: other.ref, }); ``` A copy has its original's settings (its `purpose`, `placeholder` and `format` too), scripts, default value and value, and each widget's place, look, flags and actions. A push button's copy has its image, which counts as its value, and an image field's copy is an image field. Its name is the original's with the next free number: `email` becomes `email_2`, `text_1` becomes `text_2`, `billing.name` becomes `billing.name_2`. A radio group's copy keeps its buttons' values. It has its original's assignment, which you must be allowed to give: its group, which you must be allowed to put fields in, anyone, which takes `fields:set-group:all`, or none. | Option | What it does | Default | | :-------- | :------------------------------------------------------------ | :--------------- | | `page` | The page the copies go on, at the same spot from its top-left. | each on its own | | `offset` | How far each copy moves: `{ x, y }` in page points. | `{ x: 0, y: 0 }` | | `values` | Whether a copy gets its original's value. | `true` | | `widgets` | Copy only these widgets of the fields. | all of them | With `values: false` a copy has no value, as a created field has none, and a push button's copy no image. It keeps its default value, which is what a reset puts back. A signature never comes along: a signed field's copy is unsigned. It resolves what an [import](import-export#copy-the-design) resolves: | Field | What it is | | :-------- | :------------------------------------------------------------ | | `fields` | The new fields, in the order of the fields given | | `widgets` | Their widgets' rows | | `refMap` | Each copied field's ref, with its copy's | | `dropped` | What was left out, and why | A copy leaves out what an [import](import-export#whats-left-out) leaves out, with the same reasons: a field of a kind the engine doesn't know, a script or a link without `doc.forms.script`, an action the engine can't write. Everything else is copied. A ref the form doesn't have refuses the call with `NotFound`. One call names at most as many fields as a bundle holds [items](import-export#limits), 10,000 by default. More refuses the call with `PayloadTooLarge`, and nothing is copied. A copy is one change, and one undo takes all of it away. To show the same field in one more place, with the same value, use [`addWidget()`](#add-a-widget). ## Delete a widget `deleteWidget()` deletes a widget: it leaves its page, and its field when it has one. It resolves the field as it is now, or `null` for a widget that was in no field: ```ts const { field: updated } = await doc.forms.deleteWidget(widget.ref); ``` The field stays. Without widgets it isn't on any page (`widgets` is empty), until you add one again. To take a field off its pages entirely, delete the field. A widget that is its field's own dictionary (see [Good to know](#good-to-know)) is refused with `InvalidArg`: delete the field. `removeWidget()` only takes a widget out of its field. It stays on the page with the look it had, as a widget in no field (its `field` is `null`) that holds no value, until `deleteWidget()` takes it off: ```ts await doc.forms.removeWidget(field.ref, widget.ref); ``` A widget is the form's, so `page.annotations.delete()` refuses one with `InvalidArg`. ## Move and style widgets `updateWidget()` takes the widget's `ref` and the fields to change, the way `page.annotations.update()` takes an annotation's. The engine redraws the widget: ```ts const { widget: moved } = await doc.forms.updateWidget(widget.ref, { rect: { x: 300, y: 128, width: 180, height: 24 }, interiorColor: '#fff7db', }); ``` The style fields are the ones in [The widget's look](#the-widgets-look). A widget's flags, such as `hidden` and `print`, work as for other annotations; see [Annotations](/docs/engine/annotations#flags). To stop the user changing a field, set the field's `readOnly`: PDF apps ignore a widget annotation's own `readOnly`. A widget is the form's, so `page.annotations.update()` refuses one with `InvalidArg`. A signature field's widget draws its box: its background and border, in the style above. Once a mark is in it, because the field is signed or a mark was drawn in with [`setSignatureAppearance()`](/docs/engine/forms/signatures), the widget reads `hasMark: true` and shows that mark instead. Its style no longer applies, so changing it fails with `InvalidArg`; moving or resizing the widget keeps the mark. A mark that was drawn in can be taken out again, and the widget then draws its box as before. ### Turned widgets A widget's contents can turn a quarter, so that a field on a turned page reads upright, or a label runs up the page. A widget then reads like every shape that turns: its `box` is the frame its contents are laid out in, its `rotation` the turn (0, 90, 180 or 270, clockwise; `null` upright), and its `rect` where it stands on the page, the box turned. A placement takes the turn, and either the `rect` or the `box`, as a create of any shape that turns does: ```ts await doc.forms.create({ kind: 'text', name: 'side', // 24 wide and 160 tall: the text runs up the page widgets: [{ page: page.ref, rect: { x: 20, y: 120, width: 24, height: 160 }, rotation: 270 }], }); // The same widget, by the frame its text runs in widgets: [{ page: page.ref, box: { x: -48, y: 188, width: 160, height: 24 }, rotation: 270 }]; ``` A placement with both takes the `box`; one with neither fails with `InvalidArg`. An update turns a widget as it turns any shape: - `{ rotation }` turns the whole widget about its middle, so it stands the other way; - `{ rotation, box }` turns its contents and keeps it where it is, as Acrobat's Orientation does. The new `box` is the `rect` with its sides swapped; - `{ rect }` moves and resizes it, and keeps its turn. Another angle fails with `InvalidArg`. The turn is the widget's `/MK /R`, which every PDF app reads. The file holds it counterclockwise, so Acrobat's Orientation of 90° reads as `rotation: 270`. ### Stacking order Widgets are drawn above every annotation, later ones over earlier ones. `reorderWidgets()` restacks the widgets of one page: they go together, in the order you pass them, right after or before another widget of the page, or to the bottom (`'start'`) or the top (`'end'`): ```ts const { order } = await doc.forms.reorderWidgets([widget.ref], { after: other.ref }); ``` `order` is the page's widgets in their new order, as refs. Where a page's tab order follows the order of its widgets, this changes the tab order too. An annotation is never a neighbour here: `reorderWidgets()` refuses one with `InvalidArg`; restack annotations with [`page.annotations.reorder()`](/docs/engine/annotations#delete-and-reorder). ## Widget actions A widget can do something when the user clicks it (`activate`), and on its other events: the pointer entering or leaving it (`cursorEnter`, `cursorExit`), the mouse button going down and up (`mouseDown`, `mouseUp`), getting and losing focus (`focus`, `blur`), and its page opening, closing, coming into view or leaving it (`pageOpen`, `pageClose`, `pageVisible`, `pageInvisible`). `updateWidget()` takes them in `actions`, and so does each entry of `widgets` in `create()` and `addWidget()`: ```ts await doc.forms.updateWidget(widget.ref, { actions: { activate: { type: 'reset-form', fields: null, exclude: false }, focus: { type: 'javascript', script: 'app.alert("Your name as on your passport");' }, }, }); await doc.forms.updateWidget(widget.ref, { actions: { focus: null } }); // remove one ``` An action sets that event's, `null` removes it, and an event you leave out keeps its action; `actions: null` removes them all. An action runs a script (`javascript`), goes to a page (`goto`, with a destination as for [links](/docs/engine/annotations/links#link-to-a-page)), opens a web address (`uri`), runs a viewer command (`named`), shows or hides fields (`hide`), or resets or submits the form (`reset-form`, `submit-form`). More actions to run after it go in `next`. The widget's row in `doc.forms.list()` reads them back in `actions`, by event, each as the full action. A row's `actions` passed back unchanged keeps them; to change one, pass it as above. On a field stored in one object with its widget (see [Good to know](#good-to-know)), the widget's actions and the field's scripts stay apart: writing one leaves the other as it is. ## Repair a broken form Some PDFs ship a form that other PDF apps read differently: fields that show on a page but are missing from the form's list of fields, or no form at all around them. The engine reads such fields anyway ([recovered fields](/docs/engine/forms#recovered-fields)); `repair()` fixes the file, so every PDF app sees the same form: ```ts const report = await doc.forms.repair({ bakeAppearances: true }); ``` | Field | What it counts | | :------------------------ | :----------------------------------------------------------------- | | `acroformCreated` | `true` when the document had no form and now has one. | | `fieldsLinked` | Recovered fields added to the form's list of fields. | | `widgetsLinked` | Stray widgets reconnected to their field. | | `fieldsUnrepairable` | Fields stored inside another object, which can't be linked. | | `appearancesBaked` | Widgets that got a freshly drawn look. | | `needsAppearancesCleared` | `true` when PDF apps no longer need to draw the fields themselves. | With `bakeAppearances: true` (default `false`), the engine also draws every widget that has no look of its own. When the form asks PDF apps to draw its fields themselves (`needsAppearances` on the [list](/docs/engine/forms#read-the-form)), it redraws every widget and clears that request, so the form looks the same everywhere. `repair()` only changes what needs fixing. Run it twice and the second report is all zeros. A repair can't be undone, and it ends undo for every change made before it; see [Changes & undo](/docs/engine/documents/changes#what-cant-be-undone). ## Events | Event | Fired by | | :----------------------------------------- | :----------------------------------------- | | `forms.created` | `create()` | | `forms.updated` | `update()`, `setSignatureAppearance()` and `setButtonImage()` | | `forms.deleted` | `delete()` | | `forms.widgetAdded`, `forms.widgetRemoved` | `addWidget()`, `removeWidget()` | | `forms.widgetDeleted` | `deleteWidget()` | | `forms.widgetUpdated` | `updateWidget()` | | `forms.widgetsReordered` | `reorderWidgets()` | | `forms.calculationsReordered` | `reorderCalculations()` | | `forms.repaired` | `repair()` | Each event carries what the call returned, with the rows of the widgets it changed (`widgets`). See [Events](/docs/engine/concepts/events). A copy has no event of its own: `copy()` fires `forms.created` for each field it makes, as one transaction. ## Permissions Creating, changing and deleting fields, adding, moving, restacking and removing widgets and repairing the form need `doc.forms.modify`, which includes `doc.forms.fill` and `doc.forms.read`. Writing a script, or a widget action that submits the form or opens a web address, also needs `doc.forms.script`: it runs for everyone who fills the form in (see [Scripts in forms](/docs/engine/concepts/permissions#scripts-in-forms)). Removing one doesn't, and widget actions that go to a page, reset the form or show and hide fields need `doc.forms.modify` alone. So do a field's [`format`](#dates-and-times) and a push button's [`takesImage`](#an-image-field): the engine writes their scripts itself. Putting an image in a push button is filling it in: [`setButtonImage()`](#a-button-with-an-image) needs `doc.forms.fill`, or `fields:fill` for the field's group. See [Permissions](/docs/engine/concepts/permissions). A certified document doesn't allow changes to its fields: these calls fail with `ProtectedDocument`. See [Digital signatures](/docs/engine/forms/signatures#protection-what-signatures-allow). ## Good to know - **A document without a form.** The first `create()` gives the document a form. A document with no form reports `formKind: 'none'`; after `create()` it's `'acroform'`. - **Field and widget in one object.** Many PDFs store a field with a single widget as one object. Such a widget can't be removed from its field (`removeWidget()` fails with `InvalidArg`); delete the field instead. Fields the engine creates always keep the two apart. - **Widgets come with the form.** `field.widgets` names each widget (`page` and `ref`), and the form's `widgets` holds each one's row, with its `field`. `page.annotations.list()` never returns a widget. - **Checked looks in the file.** How a checkbox or radio widget's `exportValue` relates to its look in the file is in [Checkboxes with several widgets](/docs/engine/forms#checkboxes-with-several-widgets). - **Names and groups.** `billing.name` and `billing.email` are two fields in a group `billing`. `list()` returns the two fields, not the group, and an import makes the group again from the names.