Spaces:
Running
Running
File size: 1,465 Bytes
479eb2f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
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)
|