PDF forms

View Source

Use NativeElixirPdfUtilities.Forms to inspect, fill and flatten AcroForm fields. HTML rendering creates these fields by default. Drawn lines and scanned boxes have no fields to fill; use Stamp.text/3 to place text on those PDFs.

Generate and complete a form

alias NativeElixirPdfUtilities.{Forms, HtmlToPdf}

html = """
<div>Your name: <input name="full_name"></div>
<div><input type="checkbox" name="consent"> I agree</div>
"""

{:ok, pdf} = HtmlToPdf.render(html)
{:ok, fields} = Forms.fields(pdf)
{:ok, completed} = Forms.fill(pdf, %{
  "full_name" => "Cees Kettenis",
  "consent" => true
})
{:ok, flattened} = Forms.flatten(completed)
File.write!("completed.pdf", flattened)

Forms.fields/1 returns a list of field maps:

FieldMeaning
:name, :type, :valueField key, type and current value
:read_onlytrue means filling is blocked
:choicesChoice entries with :value and :label
:export_valuesDeclared radio/checkbox export values
:widgetsEach widget's one-based :page and :rect: [left, bottom, right, top] in PDF coordinates

HTML field names and compatibility

Controls become editable fields by default. Use forms: :static for artwork only.

HTML controlPDF field
Text, search, telephone, URL, email and number inputsText
PasswordMasked text; stored value remains readable
TextareaMultiline text
Checkbox / radioCheckbox / radio group
Single / multiple selectChoice field
Buttons and submit/reset/button inputsStatic artwork
Hidden inputNo output

Missing or unknown input types use Text. Type names ignore case, but whitespace is not trimmed. See other control restrictions.

Field names

Set name for stable application keys. Generated names can change with pagination.

RuleBehavior
Explicit nameNonempty HTML name becomes the key; id does not
Generated namesTEXT_1_1, CHECKBOX_1_2, RADIO_2_1, CHOICE_2_2
NumberingOne-based page and control numbers, in document order after pagination
CollisionsExplicit names reserved first; generated collisions gain _1, _2, etc.
DuplicatesRejected, except radios in the same group
HTML name restrictionsNo period or NUL. Existing PDF names may use periods for nesting
Radio groupsFollow HTML form ownership; separate owners need distinct PDF names
Radio valuesDistinct, nonempty strings; Off is reserved
Initial checked radioLast checked member wins; unnamed radios stay independent
Explicit form referenceMust identify a form; unmatched references leave the control unowned

Initial values and choices

InputValue cleanup
Text, search, telephone, passwordRemove CR/LF line breaks: A&#10;B becomes AB
URL / single emailAlso trim surrounding ASCII whitespace
Multiple emailRemove CR/LF, trim each address, rejoin with commas
TextareaKeep line breaks
Internationalized domainsNo display conversion

Invalid initial values still render. Constraints such as required and pattern affect initial HTML selectors. Filling a PDF does not rerun HTML validation. Editable required fields carry the PDF Required flag.

Choice settingBehavior
Dropdown selectionLast selected option; otherwise first enabled option
Selected disabled optionStays selected
No available selectionnil; a selected empty option returns ""
Multiple selectList of selected values
Option valuesMust be unique; explicit value preserved, otherwise collapsed option text
Display labelsNonempty label, otherwise option text
Disabled option groupsAffect initial selection; PDF viewers may still allow choosing those options

Read-only fields and placement

SettingBehavior
disabledMakes the PDF field read-only
readonlyApplies to text-entry inputs and textareas; keeps normal styling
Boolean attributesPresence enables them, even readonly="false" or disabled="false"
Read-only fillingReturns :read_only_form_field; flattening is allowed
Radio groupsAll enabled or all disabled; use static mode for mixed groups
PlacementControls cannot span pages or repeat in page furniture
Child-document controlsEditable, with separate names from Forms.fields/1; cannot repeat across pages or page furniture
Unsupported widget transformsReturn diagnostics; use static mode for artwork
HTML appearanceUses HTML styling; use [readonly] to style read-only fields
Text extractionFlatten first so values become page content

Passwords display bullets, but Forms.fields/1 returns their stored values. Filling and flattening do not redact passwords or earlier revisions.

Fill an existing PDF

{:ok, original} = File.read("application.pdf")
{:ok, fields} = Forms.fields(original)
IO.inspect(fields)
{:ok, completed} = Forms.fill(original, %{"applicant.full_name" => "Cees Kettenis"})

Use exact names from Forms.fields/1, including any parent names and periods. Filling a field updates all its widgets. Other fields, annotations, metadata and page content stay in place.

For exclusive radio groups with repeated export values, filling preserves the currently selected matching widget, or selects the first match in field order. Groups with the PDF RadiosInUnison flag select all matching widgets.

Field typeFill value
Single-line textUTF-8 string without line breaks, or nil to clear
Multiline textUTF-8 string with explicit line breaks, or nil to clear
Checkboxtrue or false
Radio groupOne declared export-value string
Single choiceOne declared value, including "" if offered, or nil to clear
Multiple choiceA list of distinct declared values, or nil to clear; PDF must allow multiple selections

nil clears a choice; "" selects its empty-value option. Unknown names, read-only fields, invalid choices and MaxLen violations return diagnostics.

Fill appearance

SettingBehavior
Default / appearance: :fitBlack DejaVu Sans, shrunk to fit, up to 12pt; 2pt inset
Line breaksExplicit breaks kept; no automatic word wrapping
AlignmentPDF left, center or right alignment preserved
Unrenderable valuesMissing glyphs or widgets too small for the inset return diagnostics
Checkboxes / radiosKeep existing Off/on artwork
Backgrounds and bordersPreserved for library-generated fields; old external text-field decorations are not reconstructed
List boxesKeep labels and redraw highlights, even when cleared; scroll to the first selection
DropdownsShow the selected label
Viewer regenerationFilled appearances are self-contained
NeedAppearancesPartial fills keep the request; filling every field clears it

To keep a library-generated field's original fonts and styling:

{:ok, completed} = Forms.fill(original, %{"applicant.full_name" => "Cees Kettenis"},
  appearance: :source)
Source appearanceBehavior
Fonts and geometryKeep original size, style and clipping; long values may be clipped
Missing glyphsReturn a diagnostic if the captured fonts cannot draw the value
No supported source templateFall back to fitted appearance
New HTML list boxesPreserve row geometry, visibility, group labels and fonts
Older / external list boxesReconstruct rows from PDF choice entries
Unsupported appearance programsInspection allowed; modifying fields returns :unsupported_form

See SVG restrictions when combining SVG and controls.

Flatten selected fields

{:ok, flat_name} = Forms.flatten(completed, fields: ["applicant.full_name"])
{:ok, filled_and_flat} = Forms.fill(original,
  %{"applicant.full_name" => "Cees Kettenis"}, flatten: true)
CallSelected fields
Forms.flatten(pdf)All supported fields
Forms.flatten(pdf, fields: names)Only those names; [] selects none
Forms.fill(..., flatten: true)Only fields supplied to that fill call

Flattening paints selected appearances into page content and removes their widgets and field-tree entries. Other fields remain editable.

DetailBehavior
StackingUses page annotation order
GeometryPreserves appearance transforms, page rotation and resource names
Hidden / NoView widgetsRemoved without painting
Print flagScreen visibility wins: print-only widgets omitted; screen-only widgets become page content
Invisible flagDoes not hide Widget annotations
Missing / degenerate visible appearanceReturns an error

Earlier values and attachments can remain in PDF history. Flattening is not secure redaction.

Unsupported structures

InputResult
XFA, pushbuttons, signatures, comb/rich-text fields, editable combo boxesUnsupported
Field/widget actions or widget-specific rotationUnsupported
Signed PDFs or signature permissionsChanges rejected
Encrypted PDFsRejected by the reader
Malformed trees, ambiguous names, widgets without a unique pageDiagnostic error
Selected field/widget /A or /AA actionsRejected, including indirect actions and chains

Inspection and edits do not sanitize a PDF. Apply your own upload policy before sharing it.

Resource limits ยท Attachments.