Skip to content

Instantly share code, notes, and snippets.

@nro-bot
Last active January 2, 2019 21:58
Show Gist options
  • Save nro-bot/976539d222f6562ac0ec11d8e37bd647 to your computer and use it in GitHub Desktop.
Save nro-bot/976539d222f6562ac0ec11d8e37bd647 to your computer and use it in GitHub Desktop.
sign pdf on ubuntu while retaining fillable fields (using python)
#! /usr/bin/python
import os
import pdfrw
INVOICE_TEMPLATE_PATH = 'delay.pdf'
INVOICE_OUTPUT_PATH = 'delay_pdfrw2.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)
annotations = template_pdf.pages[0][ANNOT_KEY]
for annotation in annotations:
if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
if annotation[ANNOT_FIELD_KEY]:
annotation.update(pdfrw.PdfDict(AP=''))
key = annotation[ANNOT_FIELD_KEY][1:-1]
if key in data_dict.keys():
annotation.update(
pdfrw.PdfDict(V='{}'.format(data_dict[key]))
)
watermark = 'sign.pdf'
wmark = pdfrw.PageMerge().add(pdfrw.PdfReader(watermark).pages[0])[0]
page = template_pdf.pages[0]
pdfrw.PageMerge(page).add(wmark, prepend=True).render()
pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
data_dict = {'Student Name': 'asdf',
'Advisor Name': 'Prof. asdf ',
'Email Address': 'asdf',
'Date Submitted': '03 Jan 2019',
'Research Topic': 'asdf',
'Advisor': 'Prof. asdf',
"Advisor's Nominee": 'Prof. asdf',
"Student's Nominee": 'Prof. sadf',
"Dean's Nominee": None,
'Month and Year': '09/2019', 'Rationale': "asdf",
"Advisor's Comments": None}
if __name__ == '__main__':
write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict)
~
~
  1. Open libreoffice, stick in signature in correct place (and anything else you want to "merge" on as a watermark
  2. export as "sign.pdf"
  3. Run (v3) rui@chaiX1YG2:~/Downloads$ python fill_pdfrw2.py

NOTE: dictionary comes out as all one line. to get it into separate lines as above, use in vim

s/,/, \r/g

(\r inserts a new line)

$ python
from PyPDF2 import PdfFileReader
infile = 'delay.pdf'
pdf_reader = PdfFileReader(open(infile, "rb"))
dictionary = pdf_reader.getFormTextFields() # returns a python dictionary
print(dictionary)
{'Student Name': 'asdf', 'Advisor Name': 'Prof. asdf ', 'Email Address': 'asdf', 'Date Submitted': '03 Jan 2019', 'Research Topic': 'asdf', 'Advisor': 'Prof. asdf', "Advisor's Nominee": 'Prof. asdf', "Student's Nominee": 'Prof. sadf', "Dean's Nominee": None, 'Month and Year': '09/2019', 'Rationale': "asdf", "Advisor's Comments": None}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment