1

I am trying to fill form data using pdfrw library in Python 3.x. So basically I followed this tutorial - link to create the script for the task.

import os
import pdfrw


INVOICE_TEMPLATE_PATH = 'TATA AIG.pdf'
INVOICE_OUTPUT_PATH = 'output.pdf'


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


def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path)
    annotations = template_pdf.pages[0][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():
                    annotation.update(
                        pdfrw.PdfDict(V='{}'.format(data_dict[key]))
                    )
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)


data_dict = {
    'patient_name': 'Anurag Sharma'
}

if __name__ == '__main__':
    write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict)

The form is getting filled by I can't see it unless I click on it.

enter image description here

After mouse click -

enter image description here

The field data is also not visible on print preview. How do I make it a normal pdf without any clickable fields after generation?

Anurag-Sharma
  • 4,278
  • 5
  • 27
  • 42

2 Answers2

2

The following has worked for me for Adobe Reader, Acrobat, Skim, and Mac OS Preview.

pdf = PdfReader(<path>)
# ... write fields here
for page in pdf.pages:
    annotations = page.get("/Annots")
    if annotations:
        for annotation in annotations:
            annotation.update(PdfDict(AP=""))
pdf.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject("true")))

Adapted from a combination of https://github.com/pmaupin/pdfrw/issues/84#issuecomment-463493521 and https://github.com/pmaupin/pdfrw/issues/84#issuecomment-385275811.

Kent Shikama
  • 3,910
  • 3
  • 22
  • 55
0

A little adaption from the previous answer

pip install pdfrw
import pdfrw

pdf = pdfrw.PdfReader("<input_name>")
for page in pdf.pages:
    annotations = page.get("/Annots")
    if annotations:
        for annotation in annotations:
            annotation.update(pdfrw.PdfDict(AP=""))
                        
pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
pdfrw.PdfWriter().write("<output_name>", pdf)
mch22
  • 101
  • 1
  • 2