Skip to content

Instantly share code, notes, and snippets.

@nikhilweee
Last active March 5, 2024 03:08
Show Gist options
  • Save nikhilweee/ba31e425f6e5fe8937d542f5e6bcc7f0 to your computer and use it in GitHub Desktop.
Save nikhilweee/ba31e425f6e5fe8937d542f5e6bcc7f0 to your computer and use it in GitHub Desktop.
Unlock readonly form fields in a PDF
# pip install pypdf
from pypdf import PdfReader, PdfWriter
from pypdf.generic import NameObject, NumberObject
from pypdf.constants import FieldDictionaryAttributes as FA
MIN_HEIGHT = 30
reader = PdfReader("locked.pdf")
for page in reader.pages:
if "/Annots" not in page:
continue
for field in page["/Annots"]:
fo = field.get_object()
height = fo["/Rect"][3] - fo["/Rect"][1]
title, value = fo.get("/T"), fo.get("/V")
print(height, title, value)
ffbits = [FA.FfBits.DoNotScroll]
if height > MIN_HEIGHT:
ffbits += [FA.FfBits.Multiline]
# Omitting FA.FfBits.ReadOnly makes field editable
fo[NameObject("/Ff")] = NumberObject(sum(ffbits))
writer = PdfWriter(clone_from=reader)
writer.write("multiline.pdf")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment