Search code examples
pythonpdfrw

Updated pdf fields don't show up when page is written


I updated the pdf fields by using Python package pdfrw and created a new pdf. But the updated fields don't show up when I open it with Adobe Reader. However, the fields are able to show with manual clicks.

I've tried the code pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))). It indeed added an attribute NeedAppearances, but it does not solve the problem.

My code

def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    try:
        pdf = pdfrw.PdfReader(input_pdf_path)
        for page in pdf.pages:
            annotations = page['/Annots']
            if annotations != None:
                for annotation in annotations:
                    if annotation['/Subtype'] == '/Widget':
                        if annotation['/T']:
                            key = annotation['/T'][1:-1]
                            if key in data_dict.keys():
                                annotation.update(
                                    pdfrw.PdfDict(V='{}'.format(data_dict[key]))) 
        pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))) 
        print (pdf.Root.AcroForm)
        output_pdf = output_pdf_path 
        pdfrw.PdfWriter().write(output_pdf, pdf)
    except ValueError:
        pass

I expect the fields to be shown.


Solution

  • You can use annotation.update(pdfrw.PdfDict(AP=data_dict[key],V=data_dict[key])) and if you add Ff=1 then you create a PDF in read-only mode which mean you can't edit it.