1

Have been trying to put an image into a PDF file using PyMuPDF / Fitz and everywhere I look on the internet I get the same syntax, but when I use it I'm getting a runtime error.

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

I've tried a few different variations on this, with pixmap and without, with overlay value set, and without. The PDF file exists and can be opened with Adobe Acrobat Reader, and the image file exists - I have tried PNG and JPG.

Thank you in advanced for any help.

Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
AlexJ
  • 11
  • 1
  • 3

1 Answers1

2

just some hints to attempt:

Ensure that your "Image01.jpg" file is open and use the full path.

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

To ensure that you are actually on the pdf page that you expect to be, try this. This code will insert the image only on the first page

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