将图像写入 PDF 文件

Writing image into a PDF File

正在尝试将图像写入 pdf 文件的特定位置。在此代码中,“Reporting.pdf”文件包含一个模板,我必须在其中粘贴图像。 运行 此代码时,输​​出的 pdf 文件与“Reporting.pdf”文件保持相同,即图像不会写在 pdf 上。你能帮我解决这个问题吗?

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()

您不能只对文件路径执行 drawImage。 考虑使用 ImageReader:

from reportlab.lib.utils import ImageReader

reader = ImageReader(imgPath)

imgDoc.drawImage(reader, ...)