Created
March 6, 2024 18:08
-
-
Save zshanabek/d699105fb3d786a85e03f13e8bcc67ee to your computer and use it in GitHub Desktop.
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
import io | |
from PyPDF2 import PdfReader, PdfWriter | |
from reportlab.lib.pagesizes import A4 | |
from reportlab.pdfbase import pdfmetrics | |
from reportlab.pdfbase.ttfonts import TTFont | |
from reportlab.pdfgen.canvas import Canvas | |
from server.models.contract import Contract | |
class LoanDocumentHandler: | |
def get_watermark(self, contract: Contract) -> io.BytesIO: | |
packet = io.BytesIO() | |
canvas = Canvas(packet, pagesize=A4) | |
# set font, because default fonts don't support utf-8 | |
pdfmetrics.registerFont( | |
TTFont('GothamProMedium', 'GothamProMedium.ttf')) | |
canvas.setFont("GothamProMedium", 10) | |
canvas.drawString(350, 709, str(contract.amount)) | |
canvas.showPage() | |
canvas.save() | |
return packet | |
def generate_doc_pdf(self, contract: Contract) -> io.BytesIO: | |
buffer = io.BytesIO() | |
output = PdfWriter() | |
watermark = self.get_watermark(contract) | |
existing_pdf = PdfReader('p2pcontract.pdf') | |
watermark_obj = PdfReader(watermark) # read your existing PDF | |
for page_number in range(len(existing_pdf.pages)): | |
watermark_page = watermark_obj.pages[page_number] | |
existing_pdf_page = existing_pdf.pages[page_number] | |
existing_pdf_page.merge_page(watermark_page) | |
output.add_page(existing_pdf_page) | |
output.write(buffer) | |
return buffer | |
pdf_service = LoanDocumentHandler() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment