BharatKalluri
8/30/2018 - 11:50 AM

sign docs

sign docs

"""Script to generate templates and merge with docs to sign them"""

import io
from fpdf import Template
from PyPDF2 import PdfFileWriter, PdfFileReader

from base64 import b64encode, b64decode

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(inp_doc, template):
    output = PdfFileWriter()
    input_pdf = PdfFileReader(b64decode(inp_doc))
    template = PdfFileReader(b64decode(template))
    for i in range(input_pdf.getNumPages()):
        input_pdf.getPage(i).mergePage(template.getPage(0))
        output.addPage(input_pdf.getPage(i))


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()
    s_out = io.StringIO()

    # temp_doc.render('template_def_out.pdf')

    out_str = temp_doc.render(None, dest='S')
    s_out.write(out_str)
    s_out.seek(0)

    b_out = io.BytesIO()
    # print(s_out.read())
    b_out.write(bytes(s_out.read(), 'UTF-8'))
    # print(b_out.tell())
    merged_out = merge_docs_by_io(b_out, b_out)
    # print(merged_out)
    # b = io.StringIO()
    # merged_out.write(b)
    # with open('merged_out.pdf', 'w') as f:
    #     f.write(b.read())
        # pass

    # return temp_doc.render(None, dest='S')
    # return temp_doc.pdf.output(None, dest="S")


if __name__ == "__main__":
    sign_template = create_sign_template(
        {
            "Signed by": "Bharat",
            "Reason": "Loan Document",
            "Signed on": "15/5/2018",
            "Remark": "Signed using mobile and otp",
        }
    )
    # b = io.StringIO()
    # b.write(sign_template)
    # b.seek(0)
    # with open('template_out.pdf', 'w') as f:
    #     f.write(b.read())
    # print(b.read())
    # inp_doc = open("./sample.pdf", "rb").read()
    # print(b64encode(inp_doc))
    # out = merge_docs(inp_doc, sign_template)













# def create_template(el_dict):
#     """Creates template using the dict from create_elements"""
#     elements = create_elements(el_dict)
#     f = Template(format="A4", elements=elements)
#     f.add_page()
#     out = str()
#     f.render(out)


# def sign_doc(inp_doc, template_doc):
#     output = PdfFileWriter()
#     input_pdf = PdfFileReader(inp_doc)
#     template = PdfFileReader(template_doc)
#     for i in range(input_pdf.getNumPages()):
#         input_pdf.getPage(i).mergePage(template.getPage(0))
#         output.addPage(input_pdf.getPage(i))
#     outputStream = open("PyPDF2-output.pdf", "wb")
#     output.write(outputStream)


# create_template(
#     {
#         "Signed by": "Bharat",
#         "Reason": "Loan Document",
#         "Signed on": "15/5/2018",
#         "Remark": "Signed using mobile and otp",
#     },
#     "./template.pdf",
# )
# sign_doc("./sample.pdf", "./template.pdf")