Created
May 31, 2018 07:22
-
-
Save ppLorins/67da9df1bffef95cab46349b62d81a7f to your computer and use it in GitHub Desktop.
demonstrate a pdfrw problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import pdfrw | |
INVOICE_TEMPLATE_PATH = 'sample-template.pdf' | |
INVOICE_OUTPUT_PATH = 'sample-output.pdf' | |
ANNOT_KEY = '/Annots' | |
ANNOT_FIELD_KEY = '/T' | |
ANNOT_VAL_KEY = '/V' | |
ANNOT_RECT_KEY = '/Rect' | |
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: | |
annotations = page[ANNOT_KEY] | |
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]))) | |
pdfrw.PdfWriter().write(output_pdf_path, template_pdf) | |
data_dict = { | |
'field_1':'im field_1 value', | |
'field_2':'im field_2 value', | |
'options_1':True, | |
'options_2':False, | |
} | |
write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment