7

Is there a tool to fill PDF forms non-interactively from the shell?

For my use case, just setting the text for each field (in whatever order the fields are defined) and saving the PDF file would be enough, but to keep the question more general, any form interaction via CLI is appreciated (tick boxes, select radio buttons, fill text, click buttons, etc.).

I know that poppler has some functions to access PDF forms, but I couldn't find a CLI utility that makes use of these, yet.

eike
  • 478
  • 4
  • 15

1 Answers1

15

Yes, pdftk has this option. From man pdftk

fill_form <FDF data filename | XFDF data filename | - | PROMPT>

Fills the single input PDF's form fields with the data from an FDF file, XFDF file or stdin. Enter the data filename af‐ ter fill_form, or use - to pass the data via stdin, like so:

pdftk form.pdf fill_form data.fdf output form.filled.pdf

How to do?

1. Extraxt field names

pdftk forms.pdf dump_data_fields

will drop a list with e.g. entries like:

---
FieldType: Text
FieldName: Name_Last
FieldNameAlt: LAST
FieldFlags: 0
FieldJustification: Left
---

2. Create fdf-file

fdf-files are form-fillers. We use the general notation as

<< /T(FIELD_NAME)/V(FIELD_VALUE) >>

And need to add a header and footer. Source

%FDF-1.2
1 0 obj<</FDF<< /Fields[
<< /T (Name_Last) /V (Smith) >>
<< /T (Name_First) /V (John) >>
] >> >>
endobj
trailer
<</Root 1 0 R>>
%%EOF

To be saved as input.fdf

3. Create the document

pdftk forms.pdf fill_form input.fdf output filled.pdf

4. Maybe you want to check again?

pdftk filled.pdf dump_data_fields

---
FieldType: Text
FieldName: Name_Last
FieldNameAlt: LAST
FieldFlags: 0
FieldValue: Smith
FieldJustification: Left
---

So the last name has made it into the document.

5. Additional handlings

For radio buttions, the value is one of the FieldStateOption-entries, for checkboxes use V(Yes) and /V(Off).


If you want to make it more of a line-by-line query type of thing, you might want to wrap a script around it that reads the field types and names and prompts for input, then automatically creates the fdf-file. But that is a small project of its own.

Alternatively, you might like the xfdf-format better. It is based on xml-style entries. See here.

FelixJN
  • 12,616
  • 2
  • 27
  • 48
  • Thank you for this very detailed answer. XFDF seems to be more easily generated (given that there are xml libraries for every language/framework), so that's what I will probably try first. – eike Apr 01 '21 at 10:23
  • That seems to only work for filling forms reported in the FDF/XFDF file. How can a apply an FDF/XFDF file of annotations (I exported the FDF/XFDF file from Acrobat) to a PDF? – Geremia Mar 22 '23 at 03:47
  • @Geremia - that is a separate question – FelixJN Apr 14 '23 at 16:19