The problem
You fill a form with pypdf and pass flatten=True, expecting a locked, read-only PDF. The text shows up on the page, but the fields are still in the file, and a viewer that supports forms can still let people click into them.
The cause
Per the pypdf docs, flatten=True "adds the annotation's appearance stream to the page contents" and "does not remove the annotation itself." So you end up with the value drawn on the page and the original widget still sitting on top of it. In a test with a one-field form, get_fields() still returned the field after flattening.
The fix
After the values are drawn, remove the widget annotations and then the AcroForm dictionary that lists the fields.
from pypdf import PdfReader, PdfWriter
from pypdf.generic import NameObject
writer = PdfWriter()
writer.append(PdfReader("form.pdf"))
# 1. Burn each field's appearance into the page content (page=None means all pages).
writer.update_page_form_field_values(
None,
{"full_name": "Ada Lovelace"},
auto_regenerate=False,
flatten=True,
)
# 2. Remove the widgets, then the form dictionary that lists them.
writer.remove_annotations(subtypes="/Widget")
del writer.root_object[NameObject("/AcroForm")]
with open("flattened.pdf", "wb") as f:
writer.write(f)I ran this against a generated one-field form with pypdf 7.1.0. Afterward get_fields() returned None, the page had no annotations left, and the text extracted as "Name: Ada Lovelace".
Caveats
This removes every widget in the file, so any field you did not pass in the dictionary is lost too. If you need to flatten only some fields, fill and flatten those on a separate copy. Also keep the original unflattened PDF, because once the fields are gone you cannot edit the values again without refilling from the source. Finally, pypdf's own docs recommend root_object for read access only, so pin your pypdf version and re-test after upgrades.
Back to All Questions