Spaces:
Sleeping
Sleeping
| import pdfrw | |
| import io | |
| import base64 | |
| ANNOT_KEY = '/Annots' | |
| ANNOT_FIELD_KEY = '/T' | |
| ANNOT_RECT_KEY = '/Rect' | |
| SUBTYPE_KEY = '/Subtype' | |
| WIDGET_SUBTYPE_KEY = '/Widget' | |
| def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict): | |
| """填写pdf模板并输出新的pdf""" | |
| template_pdf = pdfrw.PdfReader(input_pdf_path) | |
| pdf_pages = len(template_pdf.pages) | |
| template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))) | |
| for pagenum in range(pdf_pages): | |
| annotations = template_pdf.pages[pagenum][ANNOT_KEY] | |
| if annotations is None: | |
| continue | |
| 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])) | |
| ) | |
| pdf_stream = io.BytesIO() | |
| pdfrw.PdfWriter().write(pdf_stream, template_pdf) | |
| base64.b64encode(pdf_stream.getvalue()) | |
| data_dict = { | |
| 'name': '宋有哲', | |
| "conference": "世界教育者大会" | |
| } | |
| INVOICE_TEMPLATE_PATH = "src/assets/GuestPage.pdf" | |
| INVOICE_OUTPUT_PATH = 'output/output.pdf' | |
| if __name__ == '__main__': | |
| write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict) | |