使用Python将图像添加到PDF文件

时间:2020-08-01 06:55:15

标签: python pdf pypdf2

我正在尝试构建一个系统,用户可以通过对其进行签名来验证PDF报告,因此,当用户对报告感到满意时,他们可以运行脚本,并且它将在底部添加带有其签名的图像。我尝试使用fitzPyPDF2。如果使用fitz,则在PyCharm上安装软件包时会出现问题,如果使用PyPDF2,我将无法使用任何相关选项。有人可以给我一些建议吗? (我正在使用Python 3.8)

2 个答案:

答案 0 :(得分:0)

我对此不太了解,但是我发现了一些可以帮助您的东西:

http://pybrary.net/pyPdf/


from pyPdf import PdfFileWriter, PdfFileReader

output = PdfFileWriter()
input1 = PdfFileReader(file("document1.pdf", "rb"))
watermark = PdfFileReader(file("watermark.pdf", "rb"))

input1.mergePage(watermark.getPage(0))

# finally, write "output" to document-output.pdf
outputStream = file("document-output.pdf", "wb")
output.write(input1)

outputStream.close()

我认为这就像一个水印,请参阅手册以获得更好的主意。

答案 1 :(得分:0)

当我尝试在PyCharm中安装fitz软件包时,它抛出了一个错误。但是,当我继续以下代码时

import fitz
from PIL import Image

input_file = "sample_report.pdf"
output_file = "signed sample_report.pdf"
#signature_file = "stamp.jpg"
#In case there is no image inversion problem. Also skip the line 8 to line 13 and no need for PIL import.
"""
image_file = Image.open("stamp.jpg")
image_file_rotate = image_file.transpose(Image.FLIP_LEFT_RIGHT)
image_file_rotate.save("stamp_rotated.jpg")
#Image of stamp is first rotated on it's vertical axis

image_file = Image.open("stamp_rotated.jpg")
image_file_inverted = image_file.rotate(180,expand=True)
image_file_inverted.save("stamp_inverted.jpg")
#Image of stamp is inverted to suit the visual perception
"""
signature_file = "stamp_inverted.jpg"

#Line no. 8 to 18 are attempted while countering the image inversion problem

image_rectangle = fitz.Rect(-80,-120,-540,-140)
#This step is crafting the image-box to be stamped on the input PDF file. 
fitz.Rect(x1,y1,x2,y2)
#The parameters being passed in the Rect() function are the top-left corner coordinate(x1,y1) and the bottom-right corner coordinate(x2,y2)

file_handle = fitz.open(input_file)
target_page = file_handle[0]
#The target page is retrieved. The '0' signifies no change in layout.

target_page.insertImage(image_rectangle, filename=signature_file)
#Inserting the image on the target page.
file_handle.save(output_file)
#Output is generated

现在,尽管此代码大部分用于处理图像反转问题,但我仍在努力解决定位问题。在代码中传递的坐标

image_rectangle = fitz.Rect(-80,-120,-540,-140)

在未指定参考点的意义上不清楚。并非左上角是(0,0)坐标。它可以在任何地方。而且我无法弄清楚如何检测到它并相应地定位我的图像。

相关问题