-
Notifications
You must be signed in to change notification settings - Fork 530
How to Add Form Fields
Starting with version v1.13.11, form field annotations (also called "widgets") can be added to a new or existing PDF. Since v1.13.12, existing widgets can also be updated.
If necessary, the first added widget will turn the PDF into a "Form PDF".
Widgets represent an annotation type with many special features and disparate subtypes. To present a manageable programmer API, covering a broad range of functions, we have introduced a new class, called Widget
, which serves as a "communication vehicle" in the following way:
-
To access complete widget information of a widget annotation
annot
on a page, consult its propertyannot.widget
which is aWidget
object (orNone
for other annotation types). Among its attributes are field name and field value. Demo script list-fields.py prints all information of all widgets of a PDF. -
To add a widget on a page, use the following sequence of instructions:
widget = fitz.Widget() # create a new empty widget object
widget.rect = fitz.Rect(...) # where to locate the field
widget.field_type = fitz.ANNOT_WG_TEXT # set other properties
widget.field_name = "some text field" # ... like field name, field value, etc
widget.field_value = "carpe diem!"
...
annot = page.addWidget(widget) # add the widget
# now the PDF has eventually become a Form PDF
# and further widgets can be added to this or other pages
...
doc.save(..., clean = True) # use the clean option!
Demo script widgettest.py creates a new PDF page with 5 different form fields. The result looks like this: widgettest.pdf.
Note: not all PDF viewers behave exactly equal when displaying the PDF. For example, the checkbox may not be shown correctly with its tickmark in some cases.
- To change an existing widget, use code like so:
annot = ... # widget annotation
widget = annot.widget # get widget properties
if not widget:
raise ValueError("not a widget") # that is no pdf field!
widget.field_value = "updated value" # change field value
annot.updateWidget(widget) # write changes back to field
...
# again, use clean option when saving PDF
doc.save(..., clean = True, ...)
HOWTO Button annots with JavaScript
HOWTO work with PDF embedded files
HOWTO extract text from inside rectangles
HOWTO extract text in natural reading order
HOWTO create or extract graphics
HOWTO create your own PDF Drawing
Rectangle inclusion & intersection
Metadata & bookmark maintenance