Editing Form Fields in a PDF

Guide on how to edit form fields in a PDF using PyMuPDF, including updating values and saving changes.

December 4, 20265 min readIntermediateProcessingFormsPyMuPDF 2.2

This notebook shows how to use PyMuPDF's FormFields class to:

  1. Export modifiable form fields to a CSV file
  2. Import a CSV file with value changes back into the PDF
  3. Detect and repair common structural issues of Form PDFs
import pymupdf # ensure version is at least 2.2
assert pymupdf.__version__ >= "2.2"

1. Export Modifiable Fields to CSV

doc = pymupdf.open("Customer-Info-1.pdf")
ff = doc.get_form_fields(repair=True, verbose=True)

Display terminal fields and their values.

for name,entry in ff.fields.items():
    if entry["terminal"]:
        print(f"{name:<25} '{entry['value']}'")
Output
Customer.Name.First       'John'
Customer.Name.Last        'Doe'
Customer.Fullname         'John Doe'
Customer.Address.Street   '123 Birch Street'
Customer.Address.City     'Lakeside'
Customer.WordOfMouth      'Yes'
Customer.MaritalStatus    'married'

Export fields that have a value ("terminal fields") to a CSV file.

ff.to_csv("temp.csv")

Now change some field values in the CSV file. You could do this by hand in any editor or spreadsheet; here we do it in code.

Each new value goes in the new_value column (the last one). current_value only shows what the field holds now, and from_csv() ignores it. For radio buttons and choice fields, the new value must be one of the options listed under choices.

We change the first name, last name and marital status:

import csv

new_values = {
    "Customer.Name.First": "Jane",
    "Customer.Name.Last": "Miller",
    "Customer.MaritalStatus": "single",
}

with open("temp.csv", newline="") as f:
    rows = list(csv.DictReader(f))

for row in rows:
    if row["field"] in new_values:
        row["new_value"] = new_values[row["field"]]

with open("temp.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=rows[0].keys())
    writer.writeheader()
    writer.writerows(rows)

print(open("temp.csv").read())
Output
field,type,format,editable,choices,current_value,new_value
Customer.Name.First,text,string,yes,,John,Jane
Customer.Name.Last,text,string,yes,,Doe,Miller
Customer.Fullname,text,string,yes,,John Doe,
Customer.Address.Street,text,string,yes,,123 Birch Street,
Customer.Address.City,text,string,yes,,Lakeside,
Customer.WordOfMouth,checkbox,boolean,yes,,Yes,
Customer.MaritalStatus,radio,string,yes,married|single,married,single

2. Import CSV File with Value Changes

doc = pymupdf.open("Customer-Info-1.pdf")
ff = doc.get_form_fields(repair=True, verbose=True)

Show all terminal fields and their current values before the import.

for name, entry in ff.fields.items():
    if entry["terminal"]:
        print(f"{name:<25} '{entry['value']}'")
Output
Customer.Name.First       'John'
Customer.Name.Last        'Doe'
Customer.Fullname         'John Doe'
Customer.Address.Street   '123 Birch Street'
Customer.Address.City     'Lakeside'
Customer.WordOfMouth      'Yes'
Customer.MaritalStatus    'married'

Now import the CSV file with any field value changes.

ff.from_csv("temp.csv")
Output
Fields successfully updated: 3.
from_csv(temp.csv) completed.

Method from_csv() automatically executes any cross-field JavaScripts and finally updates the FormFields object via method refresh().

Show fields again to see the changes:

We have changed Customer.Name.First, Customer.Name.Last and Customer.MaritalStatus; the field Customer.Fullname has been updated automatically via JavaScript.

for name, entry in ff.fields.items():
    if entry["terminal"]:
        print(f"{name:<25} '{entry['value']}'")
Output
Customer.Name.First       'Jane'
Customer.Name.Last        'Miller'
Customer.Fullname         'Jane Miller'
Customer.Address.Street   '123 Birch Street'
Customer.Address.City     'Lakeside'
Customer.WordOfMouth      'Yes'
Customer.MaritalStatus    'single'

To confirm the updates, we save the resulting PDF.

doc.save("Customer-Info-2.pdf", garbage=3, pretty=True)

3. Repairing Form Field Issues

This section shows ways to detect and repair common structural issues of Form PDFs by using the FormFields class.

During construction via the Document method get_form_fields() three counters are built that inform about detected issues:

To produce a display of these numbers use get_form_fields(verbose=True).

To request automatic repair use get_form_fields(repair=True).

Field-Widgets

A form field and a widget annotation are conceptually different objects:

  • A widget annotation represents the visual aspect of a form field. It is shown on some page and is referenced by the page's /Annots array. Its properties define the position on the page, text color, background color, font size, etc.
  • A form field contains all the non-appearance related properties like field name, field value, field type and several more. It is visually represented by one ore more widget annotations on one or more pages.
  • A form field refers to its widgets via its /Kids array.
  • A widget refers back to its owning form field via its /Parent key.

A "field-widget" is an object that contains all of the above information in one PDF object. This approach may be comfortable, but there is a price to pay: hard to maintain, hard to disambiguate, programmatically cumbersome, incapable of expressing complex data structures (such as hierarchies). The PDF specification explicitly discourages this practice. For more background information, please also refer to field-widget in the documentation.

Correction

PyMuPDF's FormFields class can detect and optionally repair field-widgets by splitting these objects into their two components: a form field and a widget annotation.

doc = pymupdf.open("field-widgets.pdf")
ff = doc.get_form_fields(verbose=True)  # do not repair, but tell us any problems
Output
Found PDF specification issues:
flat RBGs: 0
   flat fields: 0
   field-widgets: 6
Repair is recommended.

This file has 6 field-widgets. We could walk through the FormFields object and selectively invoke a repair, for instance:

for name, entry in ff.fields.items():
    if entry["is_widget"]:  # this is a field-widget!
        ff.repair_field_widget(name)
ff.refresh()  # reflect changes in the ff object
print(f"{ff.count_field_widgets} remaining field-widgets")
Output
0 remaining field-widgets

The more comfortable approach is the conversion at FormFields construction time:

doc.close()  # recycle the document
doc = pymupdf.open(doc.name)

ff = doc.get_form_fields(repair=True, verbose=True)
Output
Found PDF specification issues:
flat RBGs: 0
   flat fields: 0
   field-widgets: 6
Repair has been requested ...
Repairs applied in 0.00 seconds.

Flat Radio Button Groups ("flat RBG")

Here is PyMuPDF's concise definition of a "flat RBG".

When switching between the On-Off states of radio buttons programmatically, flat RBGs pose a major challenge.

This is because the buttons of the group have no structural connection to each other, like a common parent. The only thing that makes them a group is the common field name.

Therefore, the Document must be parsed in its entirety up front to identify lists of button widgets with equal names.

Correction

During its construction, FormFields detects flat RBGs and sets entry["rbg_type"] = "flat" in this case. Optionally, an automatic repair can be requested.

doc = pymupdf.open("flat-rbg.pdf")
ff = doc.get_form_fields(repair=True, verbose=True)
Output
Found PDF specification issues:
flat RBGs: 1
   flat fields: 0
   field-widgets: 0
Repair has been requested ...
Repairs applied in 0.00 seconds.

We can also work selectively here:

doc.close()
doc = pymupdf.open(doc.name)
ff = doc.get_form_fields()
for name, entry in ff.fields.items():
    if entry["rbg_type"] == "flat":  # this is a field-widget!
        ff.repair_flat_rbg(name)
ff.refresh()  # reflect changes in the ff object
print(f"{ff.count_flat_rbgs} remaining flat RBGs")
Output
0 remaining flat RBGs

Flat Fields

Flat fields are similar to flat RBGs. They are represented by a set of more than one field-widgets having the same field name. This makes them work like aliases of each other.

While capable PDF viewers detect the situation and propagate field value changes of one member to the rest of the set, to achieve this programmatically requires parsing the entire document as in the case of flat RBGs.

Correction

During its construction, FormFields detects and flags flat fields and can correct them automatically as shown above.

To do it selectively use this code pattern:

ff = doc.get_form_fields()
for name, entry in ff.fields.items():
    if entry.get("invalid_parent_structure", False):
        ff.repair_flat_field(name)
ff.refresh()

Find out more


Discuss This Article with the Community

Have a question, a different approach, or something you built after reading this? Share it on the forum or join the Discord, we'd love to hear from you.

PyMuPDF Logo

© 2026 Artifex Software Inc. All rights reserved.