Skip to content

Instantly share code, notes, and snippets.

@ppLorins
Created May 31, 2018 07:22
Show Gist options
  • Save ppLorins/67da9df1bffef95cab46349b62d81a7f to your computer and use it in GitHub Desktop.
Save ppLorins/67da9df1bffef95cab46349b62d81a7f to your computer and use it in GitHub Desktop.
demonstrate a pdfrw problem
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