PDFRW找不到pdf表单字段

2024-04-25 01:00:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python库pdfrw填充PDF。在使用Master pdf 4或Adobe Acrobat DC对pdf文件进行初始扫描后,我突出显示了一些字段,但遗漏了一些字段。因此,基本上我会尝试添加EditText/Textbox,默认情况下不会检测到这些字段。但是pdfrw程序没有检测到这些新添加的字段

代码-

import os
import pdfrw

filename = "Health India TPA Services Private Limited"

INVOICE_TEMPLATE_PATH = 'pre_auth_form_templates/' +  filename + '.pdf'
INVOICE_OUTPUT_PATH = filename + '_output.pdf'


ANNOT_KEY = '/Annots'           # key for all annotations within a page
ANNOT_FIELD_KEY = '/T'          # Name of field. i.e. given ID of field
ANNOT_FORM_type = '/FT'         # Form type (e.g. text/button)
ANNOT_FORM_button = '/Btn'      # ID for buttons, i.e. a checkbox
ANNOT_FORM_text = '/Tx'         # ID for textbox
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)
    for Page in template_pdf.pages:
        if Page[ANNOT_KEY]:
            for annotation in Page[ANNOT_KEY]:
                if annotation[ANNOT_FIELD_KEY] and annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY :
                    key = annotation[ANNOT_FIELD_KEY][1:-1] # Remove parentheses
                    if key in data_dict.keys():
                        if annotation[ANNOT_FORM_type] == ANNOT_FORM_button:
                            # button field i.e. a checkbox
                            annotation.update( pdfrw.PdfDict( V=pdfrw.PdfName(data_dict[key]) , AS=pdfrw.PdfName(data_dict[key]) ))
                        elif annotation[ANNOT_FORM_type] == ANNOT_FORM_text:
                            # regular text field
                            annotation.update( pdfrw.PdfDict( V=data_dict[key], AP=data_dict[key]) )
    template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)


data_dict = {
    'policy_no': '12345667',
    'tpa': '1234AE',
    'patient_name': 'Anurag Sharma',
    'address': 'Test Address',
    'patient_phone': '1234567890',
    'patient_phone2': '9999999999',
    'policy_no': 12345667,
    'male': 'M',
    'patient_dob': '29121998',
    'patient_age_year': '21',
    'patient_age_month': '6',
    'primary_doc': 'Test Name',
    'hospital_name': 'Test Hospital',
    'admission_date': '05052020',
    'discharge_date': '05072020',
    'days_of_stay': '10',
    'illness': 'Viral Fever',
    'ipdno': '12345',
    'patient_city': 'Test State',
    'patient_state': 'City',
    'patient_pincode': '123456',
    'planned': 'P',
    'medical_management': 'On'
}

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

Tags: pathkeyformfieldfordataifpdf