0

I need to use Python to fill a complete PDF file, But I've been searching for 8 hours now and all I could find is how to fill a text field in a PDF file only. I need to fill check checkboxes and also use radio buttons where you can check one but not the other, like Yes or No radio buttons or Gender radio buttons.

Here is a code I've been using with the pdfrw python module...

import pdfrw

template_pdf = pdfrw.PdfReader("template.pdf")

ANNOT_KEY = '/Annots'
ANNOT_FIELD_KEY = '/T'
ANNOT_VAL_KEY = '/V'
ANNOT_RECT_KEY = '/Rect'
SUBTYPE_KEY = '/Subtype'
WIDGET_SUBTYPE_KEY = '/Widget'

def fillPDF(data_dict):
    for page in template_pdf.pages:
        annotations = page[ANNOT_KEY]
        for annotation in annotations:
            if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
                if annotation[ANNOT_FIELD_KEY]:
                    key = annotation[ANNOT_FIELD_KEY][1:-1]
                    if key in data_dict.keys():
                        if type(data_dict[key]) == bool:
                            if data_dict[key] == True:
                                annotation.update(pdfrw.PdfDict(AS=pdfrw.PdfName('Yes')))
                        else:
                            annotation.update(pdfrw.PdfDict(V='{}'.format(data_dict[key])))
                        annotation.update(pdfrw.PdfDict(AP=''))
                    else:
                        print(key)

    template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
    pdfrw.PdfWriter().write("output.pdf", template_pdf)

This code is supposed to fill text fields and checkboxes but it doesn't work with checkboxes and it does not even detect the radio buttons.

If you have a way to check radio buttons and checkboxes with python please let me know. Thank you.

1 Answers1

-1

I think it is something silly. My code is pretty similar to yours and it works.

if key in data_dict.keys():
    if type(data_dict[key]) is str:
        annotation.update(pdfrw.PdfDict(AP=data_dict[key], V=data_dict[key]))
    elif type(data_dict[key]) is bool:
        if data_dict[key] is True:
            annotation.update(pdfrw.PdfDict(AS=pdfrw.PdfName('Yes')))
        elif data_dict[key] is False:
            annotation.update(pdfrw.PdfDict(AS=pdfrw.PdfName('')))
    else:
        pass
    annotation.update(pdfrw.PdfDict(Ff=1))  # Field non-editable.
41 72 6c
  • 1,600
  • 5
  • 19
  • 30
Rainer
  • 1
  • this is supposed to be a comment? and even if it is answer it does not provide explanation. 'pretty similar' is not something you should answer. you should answer the correct code and why this works. – AmaanK Jul 02 '21 at 08:49