Python 属性错误:'Page'对象没有属性'insertImage'



我正在尝试使用python代码向PDF添加png符号,而我正在运行的代码是我正在使用PyMuPDF并使用fitz库。

import fitz
input_file = "example.pdf"
output_file = "example-with-sign.pdf"
barcode_file = "sign.png"
# define the position (upper-right corner)
image_rectangle = fitz.Rect(450,20,550,120)
# retrieve the first page of the PDF
file_handle = fitz.open(input_file)
first_page = file_handle[0]
# add the image
first_page.insertImage(image_rectangle, fileName=barcode_file)
file_handle.save(output_file)

感谢您对"insert_image"的更正。它目前的工作方式如下:

import fitz
input_file = "example.pdf"
output_file = "example-with-sign.pdf"

# define the position (upper-right corner)
image_rectangle = fitz.Rect(450,20,550,120)
# retrieve the first page of the PDF
file_handle = fitz.open(input_file)
first_page = file_handle[0]
img = open("sign.png", "rb").read()  # an image file
img_xref = 0
first_page.insert_image(image_rectangle,stream=img,xref=img_xref)
file_handle.save(output_file)

我遇到了一个与您的问题非常相似的错误。您发布的insert_image解决方案是正确的,但我认为原因是从PyMuPDF的某个版本开始,camelCase(之前很好使用(被完全弃用,并被under_score_case取代。我认为有必要在这里标记PyMuPDF版本,以防将来有人遇到类似的错误时被这两种编码风格弄糊涂。

目前,我在PyMuPDF==1.21.0下,我很确定camelCase完全不受欢迎。因此,如果您遇到类似的错误,只需尝试将方法someMethod()转换为some_method()即可。

请参阅:文档在这里

最新更新