我正在尝试使用 python 库填充 PDF pdfrw
。在使用 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)