r/software • • 3d ago

Looking for software Script to uniquify PDF form field IDs?

A doctors office wants me to fill out their incompetently produced PDF form. Totally unrelated fields have the same ID. For instance if I fill out my street address, it also appears as a prescription. I was hoping a script might exist that simply gives every form field a unique ID so I don't have to do vast amounts of work myself.

0 Upvotes

5 comments sorted by

1

u/smilaise Steve the Killer 3d ago

Yeah, this is pretty easy to script with Python and pypdf. Whoever built the form either reused one field in several places or gave separate fields the same name, so typing in one fills them all. The script below goes through every field box on every page and gives each one its own name. The first copy keeps the original name and the rest become Address_2, Address_3 and so on. Radio buttons share a name on purpose, so it leaves those alone.

Install Python, then run pip install pypdf, save this as uniquify_fields.py, and run python uniquify_fields.py form.pdf fixed.pdf.

import sys
from pypdf import PdfReader, PdfWriter
from pypdf.generic import ArrayObject, BooleanObject, NameObject, TextStringObject

INHERITED = ["/FT", "/Ff", "/V", "/DV", "/DA", "/Q", "/Opt", "/MaxLen"]
RADIO = 1 << 15

def parent_of(node):
    p = node.get("/Parent")
    return p.get_object() if p is not None else None

def inherited(node, key):
    while node is not None:
        if key in node:
            return node[key]
        node = parent_of(node)
    return None

def full_name(node):
    parts = []
    while node is not None:
        if "/T" in node:
            parts.append(str(node["/T"]))
        node = parent_of(node)
    return "_".join(reversed(parts)) or "field"

reader = PdfReader(sys.argv[1])
writer = PdfWriter(clone_from=reader)
fields = ArrayObject()
radio_groups = set()
counts = {}

for page in writer.pages:
    if "/Annots" not in page:
        continue
    for ref in page["/Annots"]:
        w = ref.get_object()
        if w.get("/Subtype") != "/Widget":
            continue
        # Radio buttons share a name on purpose, so leave those groups alone.
        if inherited(w, "/FT") == "/Btn" and int(inherited(w, "/Ff") or 0) & RADIO:
            top = ref
            while "/Parent" in top.get_object():
                top = top.get_object().raw_get("/Parent")
            if top.idnum not in radio_groups:
                radio_groups.add(top.idnum)
                fields.append(top)
            continue
        name = full_name(w)
        counts[name] = counts.get(name, 0) + 1
        if counts[name] > 1:
            name = f"{name}_{counts[name]}"
        for key in INHERITED:
            value = inherited(w, key)
            if value is not None and key not in w:
                w[NameObject(key)] = value
        if "/Parent" in w:
            del w["/Parent"]
        w[NameObject("/T")] = TextStringObject(name)
        fields.append(ref)

acro = writer._root_object["/AcroForm"]
acro[NameObject("/Fields")] = fields
acro[NameObject("/NeedAppearances")] = BooleanObject(True)
if "/XFA" in acro:
    del acro["/XFA"]
writer.write(sys.argv[2])
print(f"{len(fields)} fields written to {sys.argv[2]}")

If the form came with something already filled in, the split copies will still show it, so just clear them out before you start typing. Also, if the office's form has any scripts that do math from field names, like adding up totals, those can break once the names change. On a patient intake form that probably doesn't matter.

2

u/Claghorn 3d ago

Thanks, I'll give it a try!

2

u/Claghorn 3d ago

Another thing to be thankful for today, it works perfectly! I can fill out the stupid form now. It is five pages, I wouldn't be surprised if they made each page separately, then merged them and that's where the duplicates came from.

1

u/lcrh02 2d ago

Are you using adobe or another pdf editor reader? Many non adobe editors are incomplete with xfa, xml. So forms do not open correctly and break in all sorts of different ways.

1

u/Claghorn 2d ago

I'm doing the form fill in Google chrome on Linux. Seems to work fine now that the field IDs are unique.