AcroForm Support

Overview

Since HotPDF v2.5.0 the library can emit interactive forms (AcroForm) per PDF 1.7 ISO 32000-1 section 12.7. Each form field is created as a Widget annotation merged with the field dictionary and is automatically registered with the document so the global /AcroForm entry is added to the catalogue when the document is finalised in EndDoc

Loaded documents can store a terminal field separately from its widget annotations in /Kids. SetLoadedAcroFormCalculationOrder writes field dictionary references to /CO in the supplied order, including those split fields, and skips unresolved names without executing JavaScript or recalculating values

Supported field types

  • Text fields (/FT /Tx) via THPDFPage.AddTextField. Supports single-line, multi-line, password, comb, file-select, rich-text, scroll and spell-check options through THPDFFormFieldFlags
  • Check boxes (/FT /Btn, no Pushbutton/Radio bits) via THPDFPage.AddCheckBox with a configurable export value name and initial checked state
  • Radio buttons (/FT /Btn /Ff Radio) via THPDFPage.AddRadioButton. Multiple calls with the same group name are merged under a shared parent field with a /Kids array, exactly as required by 12.7.4.2
  • Combo boxes (/FT /Ch /Ff Combo) via THPDFPage.AddComboBox, or AddComboBoxWithLabels for paired export values and display labels with exact selected-index identity, including empty exports
  • List boxes (/FT /Ch) via THPDFPage.AddListBox. ffMultiSelect enables multi-select
  • Push buttons (/FT /Btn /Ff Pushbutton) via THPDFPage.AddPushButton with optional caption (/MK /CA). Since HotPDF v2.31.0, THPDFPage.AddPushButtonWithAction attaches a PDF action dictionary to the widget so clicking the button runs /SubmitForm (post field values to a URL, PDF 1.2 12.7.5.2), /ResetForm (PDF 1.2 12.7.5.3), /JavaScript (run a JS snippet, PDF 1.3 12.6.4.16) or /URI (open a URL in the system browser, PDF 1.1 12.6.4.7)
  • Signature placeholder fields (/FT /Sig) via THPDFPage.AddSignatureField since HotPDF v2.12.0. The AcroForm dictionary automatically gains /SigFlags 3 (SignaturesExist + AppendOnly) when at least one signature field is present. The field is left unsigned so external tools (Adobe Acrobat, Foxit, dedicated CMS / PKCS#7 signing libraries) can attach the actual cryptographic signature after the file is saved
  • In-place signing workflow via THPDFPage.AddSignedSignatureField + THotPDF.PreparePDFForSigning + THotPDF.InsertSignatureHex since HotPDF v2.23.0. The first call reserves a /V signature dictionary with /ByteRange and /Contents placeholders. After saving the document the host application calls PreparePDFForSigning to patch /ByteRange and learn which file ranges to hash. After producing a CMS / PKCS#7 detached signature externally (Windows CryptoAPI, OpenSSL, dedicated signing libraries), it calls InsertSignatureHex to drop the signature hex into the placeholder without disturbing any other byte in the file

Generated push-button appearances display valid UTF-8 captions within the 218-character canonical printable WinAnsi profile using standard Helvetica and centre them horizontally using the matching glyph advances before PDF literal escaping, so escaped parentheses, backslashes and high-byte octal escapes do not count as extra glyphs. Existing caption storage, action metadata, vertical placement, font-size selection, left clamp and appearance-generation policy are retained. For multibyte UTF-8 captions, unsupported scalars or malformed sequences retain the whole-caption empty appearance; the original ASCII path is unchanged and general Unicode, automatic font fallback and complex shaping remain outside this finite profile

Creation-time field wrappers

Since HotPDF v2.292.12, the THPDFPage.CreateTextField, CreateCheckBox, CreateRadioButton, CreateComboBox, and CreateListBox helpers create the same AcroForm widgets as the existing Add... methods and return a lightweight THPDFAcroFormField wrapper for immediate configuration

Since HotPDF v2.292.26, THotPDF.SetFormFieldTooltip assigns the PDF /TU user hint by field name for fields created through the existing Add... methods, matching the wrapper-level THPDFAcroFormField.SetTooltip workflow

Since HotPDF v2.298.0, creation-time field APIs and loaded-document field-creation APIs reject duplicate root field names with a diagnostic exception before any widget is registered. Repeated AddRadioButton calls with the same group name remain valid because they share one parent field and add additional child widgets under its /Kids array

The wrapper exposes chainable setters for /TU tooltips, common field flags (SetReadOnly, SetRequired, SetNoExport), /DA default appearance strings, field-level additional actions such as /AA /K, /AA /F, /AA /V, /AA /C, and widget mouse or focus actions through THPDFActionBuilder

Creation-time wrapper Pascal example

Field := HPDF.CurrentPage.CreateTextField('Email', '', Rect(50, 80, 250, 104));
Action := THPDFActionBuilder.JavaScript('event.rc = event.value.indexOf("@") > 0;');
try
  Field.SetTooltip('Email address');
  Field.SetRequired(True);
  Field.SetReadOnly(False);
  Field.SetAdditionalAction(fatValidate, Action);
finally
  Action.Free;
  Field.Free;
end;

Loaded form-field inspection and updates

Since HotPDF v2.121.9, applications can load an existing AcroForm PDF with THotPDF.LoadFromFile, enumerate its fields, read their names, types and values, change field values, toggle the read-only flag, and save the loaded object graph with THotPDF.SaveLoadedDocument This path is intended for persisted edits to an already loaded document; do not call BeginDoc / EndDoc just to save loaded field-value changes

The field helpers are GetFormFieldCount, GetFormFieldName, GetFormFieldType, GetFormFieldValue, SetFormFieldValue, and SetFormFieldReadOnly. Field lookup accepts either a zero-based field index or the fully qualified field name. The returned THPDFLoadedFormFieldType values are lfftText, lfftButton, lfftChoice, lfftSignature, or lfftUnknown

Loaded-field Pascal example

HPDF.LoadFromFile('InputForm.pdf');
for I := 0 to HPDF.GetFormFieldCount - 1 do
  Writeln(HPDF.GetFormFieldName(I), ' = ', HPDF.GetFormFieldValue(I));

HPDF.SetFormFieldValue('CustomerName', 'Bob');
HPDF.SetFormFieldValue('Plan', 'Premium');
HPDF.SetFormFieldReadOnly('CustomerName', True);
HPDF.SaveLoadedDocument('UpdatedForm.pdf');

Field additional actions

The wrappers AttachFieldKeyStrokeAction, AttachFieldFormatAction, AttachFieldValidateAction, and AttachFieldCalculateAction attach JavaScript to a field's /AA dictionary for the PDF /K, /F, /V, and /C triggers. Use SetFormFieldAdditionalAction or its named THPDFActionBuilder wrappers when the same trigger must run a reusable action chain such as JavaScript, ResetForm, SubmitForm, URI, Hide, ImportData, or a chained /Next action. Widget-level mouse and focus triggers can also be installed by field name through SetFormFieldAnnotationAction and the named mouse / focus helpers, while the matching clear helpers remove one trigger without disturbing the rest of the /AA dictionary

Loaded listbox top option

When rebuilding a loaded listbox appearance, HotPDF starts the visible option window at the valid /TI index and keeps selection highlighting tied to the original /Opt indices

The lookup uses the nearest present /TI on the field or its bounded parent chain; the AcroForm dictionary is not a /TI default

A missing value starts at option zero, and a present null, invalid, fractional, negative or out-of-range value also falls back to zero for appearance only; the original field data is preserved and combo-box appearance behaviour is unchanged

Loaded password appearances

When rebuilding a loaded password text field, a valid UTF-16 surrogate pair produces one asterisk, each other BMP character produces one asterisk, and each unmatched surrogate code unit also produces one asterisk

This rule changes the generated appearance only; stored /V and /DV values and document encryption behaviour remain unchanged

Loaded-field nominal font advances

For the twelve exact Latin Base14 Type1 font names, eligible loaded-field appearances measure the actual glyph names selected by the supported effective simple-font encoding using the selected face's nominal glyph advances

The metric path uses one positive explicit font size or the supported zero-size request described below, together with the supported default-appearance subset and a font that has no descriptor or explicit /Widths, /FirstChar or /LastChar entries; the controlled absent-font-reference Helvetica fallback follows the same rule

Single-line alignment, multiline whole-word wrapping, individual comb-cell centring, combo and listbox display labels, password masks and loaded push-button captions use the same emitted-glyph measurement; literal escapes add no advance, and a substituted character measures the glyph actually selected by its emitted replacement byte

Padding, clipping, rotation, field values and resource ownership retain their existing roles; incomplete font overrides, Type0 fonts and operators outside the supported text-state subset retain their previous measurement policy, whilst eligible zero-size requests use the automatic sizing profile below

These nominal advances do not add kerning, general Unicode display, complex-script shaping or arbitrary text-state measurement

Loaded-field declared simple-font advances

Eligible loaded-field appearances use the selected Type1 or TrueType font's declared /Widths when the complete /FontDescriptor, /FirstChar, /LastChar and /Widths group is present and the code bounds and numeric table are valid

The table is indexed by the bytes the effective encoder actually emits, including replacement and password-mask bytes; direct and indirect arrays, bounds and numeric entries describe the same advances

Bytes outside the declared span use the descriptor's /MissingWidth, or zero when that entry is absent; valid zero, fractional and signed advances remain measurements rather than missing-glyph sentinels

The path uses one positive finite font size or the supported zero-size request described below, and applies to alignment, whole-word wrapping, comb cells, choice display labels and loaded push-button captions

An invalid table or an unrepresentable measurement retains the previous measurement policy for that complete run; Type0 and Type3 fonts and operators outside the supported text-state subset retain their existing behaviour

Declared advances preserve field values, actual font resources and embedded program bytes; they do not add encoding coverage, kerning, general Unicode display or complex-script shaping

Long decimal declared-width values on FPC

For supported loaded component-field declared-width measurements on FPC, long decimal numeric tokens are converted directly from their complete decimal value to the nearest Double value, with ties rounded to even

This avoids the legacy numeric input-length limit and intermediate extended-precision double rounding; finite signed values and signed zero retain their numeric meaning, whilst the original source token and saved numeric bytes are preserved

Invalid PDF numeric tokens, overflow and nonzero values that round to zero retain the existing whole-run measurement fallback rather than being accepted as valid zero widths

Short-token and Delphi conversion paths retain their previous behaviour; this finite repair does not establish correctly rounded conversion for every numeric token or compiler, broaden supported font profiles or add Type0, CFF, shaping or general dynamic XFA support

Loaded-field text-state layout

Eligible loaded-field appearances measure finite Tc character spacing, Tw word spacing and Tz horizontal scaling together with the selected nominal or declared glyph advances, including negative spacing and negative or zero horizontal scale

The finite default-appearance parser accepts one positive explicit Tf or the supported zero-size request below, an optional supported g, rg or k fill colour and the three spacing or scaling operators; repeated Tc, Tw and Tz assignments use their last value, whilst an unsupported trailing operator prevents partial metric admission

Measurement follows the bytes actually emitted after encoding, replacement or omission; Tw applies only to emitted single-byte code 32, even when the encoding maps that byte to a visible non-space glyph, and does not apply to a Unicode space encoded at another byte

Left, centre and right justification, multiline whole-word wrapping, each comb cell, choice labels and loaded captions share the union of the signed glyph advance cells after horizontal scaling; backward or mirrored runs are positioned by their minimum and maximum cell endpoints, including the natural advance cell of a space

This interval is a layout measurement, not an ink bounding box; spacing after the final glyph moves the PDF cursor but does not enlarge an independently positioned run, and comb cells use the same rule for each absolute text position

Each generated text scope initialises character spacing, word spacing and horizontal scaling before replaying its default appearance, including text scopes reopened for listbox selection highlighting, so caller text state does not leak into the field appearance

Eligible zero-size requests use the content-fitting profile below whilst preserving the other admitted default-appearance state

These component-field layout rules do not add Type0 metrics, CFF or implicit TrueType built-in encoding providers, arbitrary default-appearance execution, kerning, general Unicode display or complex-script shaping, and do not imply a new Linux headless acceptance result

Loaded-field automatic font size

Eligible loaded component fields with one Tf whose original decimal size is zero select a positive fixed-decimal size using their actual display content; legal PDF whitespace and comments can separate the font operands and operator, and a positive token that underflows to zero is not treated as an automatic-size request

Sizing follows the final emitted text after encoding, replacement, omission, password masking or choice display-label selection, using the selected nominal or declared glyph advances with finite Tc, Tw and Tz, including negative spacing and negative or zero horizontal scale

Single-line text, each occupied comb cell, combo displays and loaded push-button captions use their existing alignment and baseline contracts; multiline fields keep whole-word wrapping and check the complete wrapped value before painting rather than treating clipped trailing rows as fitted

A listbox freezes its visible option window from /TI before searching, then fits every complete row rectangle and selection highlight in that window; options outside the window do not force the size down, and the original /Opt, /V and /I data is retained

For an admitted request, only the original Tf size operand is replaced; the remaining /DA bytes, colour, spacing, horizontal scaling, field value and font resources are preserved, and explicit positive font sizes retain their existing behaviour

The fit uses glyph advance cells and the existing vertical layout cells rather than ink bounds, within the supported measurement and existing geometry-serialisation ranges; when no admitted size fits or a numeric measurement cannot be completed, a clipped preferred-size fallback retains the value, font and other admitted /DA state, and must not be interpreted as a successful content fit

This finite component-field profile does not add Type0 metrics, CFF or implicit TrueType encoding providers, complex shaping, arbitrary default-appearance execution or general dynamic XFA support, and does not imply a new Linux headless acceptance result

Automatic-size interval work for ordinary runs

Eligible automatic-size runs with zero accumulated spacing offsets, nonnegative natural advances and monotone scaled endpoints use a linear number of interval constraints within a certified finite numeric range

The shortcut still validates every emitted byte, glyph advance and required missing-width lookup, and retains the complete final fit check before using a selected size

Runs outside that certificate, including negative natural advances, nonzero accumulated spacing offsets or extreme numeric bounds, retain the complete constraint path and its existing numeric fallback behaviour

This optimisation applies to interval calculation; the cost of complete wrapping and automatic-sizing searches still depends on the content

Loaded-field default-appearance font selection

Loaded-field appearance generation reads font selection independently of the finite glyph-measurement profile: space, NUL, tab, linefeed, formfeed and carriage return are valid PDF whitespace, and comments may separate the font name, numeric size and Tf operator

Supported positive size tokens include signed and fractional decimal forms; the generated appearance keeps the original admitted default-appearance bytes, including separators and comments, whilst binding the selected input font resource

When the default appearance contains several Tf operations, its effective font and size follow the last executed assignment and any q/Q save and restore; resources referenced by earlier assignments remain bound to their original font objects

Font resource names are matched case-sensitively after one PDF name-decoding pass: F0 and F#30 share one semantic resource name, whilst a literal hash encoded through #23 is not decoded a second time

The original field /DA and /V remain unchanged; a final zero or out-of-range size outside the automatic-sizing profile retains the bounded fixed-size compatibility fallback on the effective final font, and that fallback may normalise the generated appearance's default appearance without claiming a content fit

Correct font binding does not broaden the single-font text-state metric subset: complex default appearances retain their previous glyph-measurement policy, and this repair does not add arbitrary graphics-state execution, Type0 metrics, general Unicode display, complex shaping or general dynamic XFA support

Loaded-field font encoding

Loaded-field appearances match the AcroForm /DR and /Font keys and the font's /Subtype key case-sensitively; the font resource name selected by /DA is compared case-sensitively after one PDF name-decoding pass. Distinct semantic resources such as /F0 and /f0 retain their own font dictionaries and character encodings, regardless of dictionary insertion order; an unrelated case variant does not shadow an exact resource

Loaded-field simple-font encoding

Loaded component-field appearances build the effective simple-font encoding before mapping decoded field text to glyph bytes, retaining case-sensitive font resource selection and the original font program

For supported Type1 fonts, named WinAnsi, MacRoman and MacExpert encodings and legal explicit /BaseEncoding dictionaries support sequential /Differences assignments, including nonascending segments and overridden base slots

The finite nonsymbolic TrueType coverage uses the observed /Flags 32 path with explicit WinAnsi or MacRoman bases, the original font program and byte-indexed advances; it does not establish symbolic or implicit TrueType built-in providers

The loaded component-field inverse uses the complete Adobe Glyph List associations and supported suffix, component and strict synthetic-scalar rules; multi-scalar glyph associations stay distinct during scalar lookup and are not reduced to their first scalar, without changing the global glyph-name API or adding shaping

When /BaseEncoding is absent, the supported embedded Type1 /FontFile header forms provide the actual built-in vector; eligible unembedded nonsymbolic fonts retain their Standard fallback

/StandardEncoding is not a legal PDF predefined encoding name, so it is not accepted as an explicit named base

Effective byte selection, declared advances and eligible Base14 nominal advances share the same final glyph sequence for alignment, comb cells and whole-word wrapping

Equivalent byte positions may select the same exact original glyph and advance; visible glyph identity is distinct from an arbitrary canonical-byte choice or a text-extraction map

A real mapped question glyph is preferred for replacement, with the documented legacy missing-glyph byte retained only when it does not select a different real glyph

The Type1 provider supports its implemented header forms and is not a general PostScript interpreter; CFF and implicit TrueType built-in providers, Type0 changes, arbitrary Unicode display, kerning and complex shaping remain outside this finite delivery

Headless font-supplied APIs use separate paths, so these Windows component-field rules do not imply new Linux execution acceptance

The full Standard table maps U+2022 to B7, U+0027 (apostrophe) to A9, U+0060 (backtick) to C1, U+2018 (left single quotation mark) to 60 and U+2019 (right single quotation mark) to 27; it is not an ASCII-identity encoding

When the selected font reference is absent, HotPDF creates Helvetica and uses its built-in Standard encoding; a damaged non-null font reference is not treated as this controlled fallback

The predefined PDF encoding names do not include /StandardEncoding: the Standard table is selected through the font's built-in encoding or a valid implicit-base dictionary, not by accepting that undefined name

Unsupported font programs and malformed encoding graphs retain their existing fallback policies; these finite simple-font paths do not add Type0 behaviour, arbitrary Unicode display or shaping

THPDFHeadlessDocument has separate font-supplied appearance APIs and does not execute the component's PDFTextOp path; these loaded-component encoding rules do not imply a new Linux headless acceptance result

Appearance generation

By default HotPDF pre-builds /AP /N Form XObjects (PDF 1.7 8.10) for every text field, push button, choice (combo / list) and the Yes / Off states of every checkbox / radio kid, whilst the emitted /AcroForm dictionary still sets /NeedAppearances true. A consuming viewer (Adobe Reader, Foxit, Chrome, browsers, Apple Preview) may then keep rendering appearances from each field's /DA string, and a renderer that ignores the flag draws the embedded stream instead of an empty field. Setting THotPDF.AutoFormAppearances to true before adding fields makes those streams authoritative: the AcroForm dictionary then carries /NeedAppearances false. Setting it to false writes fields with no /AP at all and leaves the rendering entirely to the viewer. A PDF/A profile and PDF 2.0 output take the authoritative shape without any call: PDF/A forbids /NeedAppearances true and PDF 2.0 deprecates it. In every case the AcroForm also carries a /DR default resources entry referencing the standard 14 base fonts (Helv Helvetica, ZaDb ZapfDingbats). Available since HotPDF v2.28.0, on by default since v2.1203.21

Field flag reference (THPDFFormFieldFlags)

  • ffReadOnly, ffRequired, ffNoExport — common Table 227 flags applicable to every field type
  • ffMultiline, ffPassword, ffFileSelect, ffDoNotSpellCheck, ffDoNotScroll, ffComb, ffRichText — Tx-specific (Table 228)
  • ffEdit, ffSort, ffMultiSelect, ffDoNotSpellCheck, ffCommitOnSelChange — Ch-specific (Table 230)

Pascal example

HPDF.BeginDoc;
HPDF.AddPage;
HPDF.CurrentPage.AddTextField('Name', '', Rect(50, 100, 250, 120));
HPDF.SetFormFieldTooltip('Name', 'Customer name');
HPDF.CurrentPage.AddCheckBox('Agree', 'Yes', Rect(50, 130, 70, 145), True);
HPDF.CurrentPage.AddRadioButton('Color', 'Red',   Rect(50, 160, 70, 175), True);
HPDF.CurrentPage.AddRadioButton('Color', 'Green', Rect(80, 160, 100, 175));
HPDF.CurrentPage.AddRadioButton('Color', 'Blue',  Rect(110, 160, 130, 175));
HPDF.CurrentPage.AddComboBox('Country', 'CN',
                             ['CN', 'US', 'JP'], Rect(50, 190, 250, 210));
HPDF.EndDoc;

Authored text-field UTF-8 appearances and Helvetica advances

New text fields created through AddTextField or CreateTextField display valid UTF-8 within the canonical printable WinAnsi profile using Helvetica; the encoded character bytes determine layout before PDF literal escaping, so escaped punctuation and high-byte octal sequences do not count as extra glyphs

Comb fields centre each encoded character's actual Helvetica advance in its cell, whilst multiline fields use those same advances to keep whole words together when they fit and split oversized words into fitting character spans

Ordinary authored multiline fields retain CR, LF and CRLF separators, intervening empty paragraphs and spaces inside each line; tabs advance to the next multiple of eight actual Helvetica space advances without emitting a TAB glyph. Whole-word wrapping may visually omit line-edge whitespace, whilst a character wider than the available line still progresses and uses the existing clip rather than claiming a fit

Password appearances use one asterisk per valid Unicode scalar, including characters outside WinAnsi; the original field value, MaxLen, flags and appearance-generation policy remain unchanged

The fixed-size path retains its existing viewport, font-size limits, leading and vertical placement; unsupported ordinary text and malformed multibyte input retain the empty-appearance fallback, and this does not add general Unicode fonts, complex shaping or ink-bound measurement

HTML textarea values and native multiline appearances

Imported textarea controls preserve their normalised literal value in /V and /DV and set the multiline field flag; Windows component callers get the real normal appearance by default and can take it away by setting AutoFormAppearances to false

The native UNIX canvas THPDFPage.AddTextField accepts an optional Multiline Boolean whose default is False, preserving existing single-line calls; True sets the multiline flag and selects actual multiline appearance generation, retaining spaces and measuring eight-space tab stops with the supplied font provider

These are separate component and native appearance contracts, with their existing fonts, clips, baselines and leading; this feature description does not imply a new Linux execution or general Unicode font coverage

Authored Helvetica zero-size content fitting

Create an ordinary text field with appearance generation on, which is the default and also what AutoFormAppearances = true gives you, then call SetDefaultAppearance with a supported zero-size request such as /Helv 0 Tf 0 g to rebuild its normal appearance immediately; the existing PDF 2.0 appearance-generation policy can also require this appearance

This finite profile accepts one exact /Helv font name with a decimal-zero Tf size and optional finite g, rg or k colour operations, including PDF whitespace and comments; it does not execute arbitrary default-appearance operators

The field retains the original zero-size /DA string, whilst the generated appearance substitutes a positive font size and preserves the requested colour; stored /V, /DV, flags and MaxLen are unchanged

Fitting uses the actual Helvetica advances of the emitted WinAnsi bytes and the existing single-line, multiline and occupied comb-cell plans; every planned row and occupied cell must fit, using the em-cell interval from one quarter of the font size below the baseline to three quarters above it inside the existing clip inset

The deterministic decreasing search can select sizes below six points or above twelve points when a complete layout fits; it promises a finite content fit, not a globally maximal size or an ink-bound guarantee, and retains the authored baseline and multiline leading rather than adopting the loaded-field layout

If no tested size fits, the existing clipped preferred-size appearance remains; unsupported ordinary text retains the existing empty-appearance fallback, and neither fallback is a successful content fit

Positive-size requests, rich-text fields and other default-appearance profiles retain their existing setter behaviour; subsequent value updates through SetFormFieldValue or THPDFLoadedFormField.SetValue continue to use the existing loaded-field automatic-size solver, whose baseline and leading can differ

Limitations

  • Standard-font appearance support remains field-specific. Generated push-button and authored combo-box captions and authored text fields accept defined WinAnsi characters from valid UTF-8 stored text; unsupported scalars or malformed sequences in the multibyte extension retain the whole-caption empty appearance. This finite standard-font profile does not provide general Unicode appearance rendering
  • Down (/D) and rollover (/R) sub-states are not generated; only the normal (/N) state is produced
  • Field names are checked for duplicate root entries when new AcroForm widgets are created; hierarchical partial-name construction beyond the radio parent / widget pattern remains the caller's responsibility

Native field creation and flag editing preserve exact 32-bit /Ff masks through saving and reloading, including inherited flags and local null entries

See AcroForm field flag precision for signed mask values, inheritance and native builder behaviour

See Also