Created
August 30, 2018 12:13
-
-
Save pskd73/12ac7dbed7acb0683bb6e04dd46a12a5 to your computer and use it in GitHub Desktop.
Merge pdfs by BytesIO
This file contains 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
"""Script to generate templates and merge with docs to sign them""" | |
import io | |
from fpdf import Template | |
from PyPDF2 import PdfFileWriter, PdfFileReader | |
def create_elements(el_dict): | |
"""Creates a elements dict to customize the template""" | |
final_dict = [] | |
assert isinstance(el_dict, dict) | |
max_height = 5 * (len(el_dict)) + 5 | |
for i in el_dict: | |
el = { | |
"name": i, | |
"type": "T", | |
"x1": -40, | |
"y1": -(max_height), | |
"font": "Arial", | |
"size": 6.0, | |
"bold": 0, | |
"italic": 0, | |
"underline": 0, | |
"foreground": 0, | |
"background": 0, | |
"align": "I", | |
"text": str(i + " : ") + str(el_dict[i]), | |
"priority": 2, | |
} | |
final_dict.append(el) | |
max_height = max_height - 5 | |
return final_dict | |
def merge_docs_by_io(inp_io, template_io): | |
output = PdfFileWriter() | |
input_pdf = PdfFileReader(inp_io) | |
template = PdfFileReader(template_io) | |
for i in range(input_pdf.getNumPages()): | |
input_pdf.getPage(i).mergePage(template.getPage(0)) | |
output.addPage(input_pdf.getPage(i)) | |
return output | |
def create_sign_template(user_content): | |
"""Generates and returns a bytearry containing the template of the sign doc""" | |
elements = create_elements(user_content) | |
temp_doc = Template(format="A4", elements=elements) | |
temp_doc.add_page() | |
temp_doc.render('template_def_out.pdf') | |
out_str = temp_doc.render(None, dest='S') | |
b_out = io.BytesIO() | |
b_out.write(out_str.encode('latin1')) | |
b_out.seek(0) | |
# Instead of sample.pdf, pass BytesIO. It works | |
md = merge_docs_by_io(b_out, 'sample.pdf') | |
m_out = io.BytesIO() | |
md.write(m_out) | |
m_out.seek(0) | |
with open('merged.pdf', 'wb') as f: | |
f.write(m_out.read()) | |
if __name__ == "__main__": | |
create_sign_template( | |
{ | |
"Signed by": "Bharat", | |
"Reason": "Loan Document", | |
"Signed on": "15/5/2018", | |
"Remark": "Signed using mobile and otp", | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment