Search code examples
python-3.xtkinter-canvasreportlabpypdf

Writing image into a PDF File


Trying to write an image into a pdf file at a specific location. Here in this code "Reporting.pdf" file contains a template where I have to paste my image. While running this code, the output pdf file remains the same as "Reporting.pdf" file i.e. the image doesn't get written on the pdf. Can you help me resolve this issue?

from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from io import BytesIO
import os
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
imgPath = os.path.join(THIS_FOLDER, 'child.png')
print(imgPath)

# Using ReportLab to insert image into PDF
imgTemp = BytesIO()
imgDoc = canvas.Canvas(imgTemp)

# Draw image on Canvas and save PDF in buffer
# imgPath = "/home/sachin/Files/child-image.jpeg"
imgDoc.drawImage(imgPath, 399, 760, 160, 160)    ## at (399,760) with size 160x160
imgDoc.save()
print(imgDoc)

# Use PyPDF to merge the image-PDF into the template
page = PdfFileReader("Reporting.pdf","rb").getPage(0)
overlay = PdfFileReader(BytesIO(imgTemp.getvalue())).getPage(0)
page.mergePage(overlay)

#Save the result
output = PdfFileWriter()
output.addPage(page)
pdfOutput = open('output_file101.pdf', 'wb')
output.write(pdfOutput)
pdfOutput.close()

Solution

  • You can't just do a drawImage with a filepath. Consider using an ImageReader:

    from reportlab.lib.utils import ImageReader
    
    reader = ImageReader(imgPath)
    
    imgDoc.drawImage(reader, ...)