簡體   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