繁体   English   中英

Python PyMuPDF Fitz insertImage

[英]Python PyMuPDF Fitz insertImage

一直在尝试使用 PyMuPDF / Fitz 将图像放入 PDF 文件中,我在互联网上看到的任何地方都得到相同的语法,但是当我使用它时,我遇到了运行时错误。

>>> doc = fitz.open("NewPDF.pdf")
>>> page = doc[1]
>>> rect = fitz.Rect(0,0,880,1080)
>>> page.insertImage(rect, filename = "Image01.jpg")

error: object is not a stream
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\fitz\fitz.py", line 1225, in insertImage
return _fitz.Page_insertImage(self, rect, filename, pixmap, overlay)
RuntimeError: object is not a stream

>>> page
page 1 of NewPDF.pdf

我已经尝试了几个不同的变体,有像素图和没有像素图,有覆盖值设置,也没有。 PDF 文件存在并且可以用 Adobe Acrobat Reader 打开,图像文件存在 - 我试过 PNG 和 JPG。

提前感谢您的帮助。

只是一些尝试的提示:

确保您的“Image01.jpg”文件已打开并使用完整路径。

image_path = "/full/path/to/Image01.jpg" 

image_file = Image.open(
    open(image_path, 'rb'))
    # side-note: generally it is better to use the open with syntax, see link below
    # https://stackoverflow.com/questions/9282967/how-to-open-a-file-using-the-open-with-statement

为确保您确实位于预期的 pdf 页面上,请尝试此操作。 此代码将仅在第一页插入图像

for page in doc:
    page.InsertImage(rect, filename=image_path)
    break  # Without this, the image will appear on each page of your pdf

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM