Skip to content

Instantly share code, notes, and snippets.

@killthekitten
Created April 9, 2019 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killthekitten/f600f96aedc04be2540f3e23f35d0870 to your computer and use it in GitHub Desktop.
Save killthekitten/f600f96aedc04be2540f3e23f35d0870 to your computer and use it in GitHub Desktop.
Illustrates Pixmap regression introduced in PyMuPDF 1.14.13
import fitz
import io
import requests
PDF_URL = "https://github.com/pymupdf/PyMuPDF/raw/master/examples/colordbHSV.pdf"
PNG_URL = "https://www.onlygfx.com/wp-content/uploads/2018/07/12-grunge-brush-stroke-banner-11.png"
def handle(_):
pdf = requests.get(PDF_URL).content
png = requests.get(PNG_URL).content
rect = fitz.Rect(0, 0, 400, 50)
document = fitz.open(stream=pdf, filetype="pdf")
for page in document:
page.insertImage(rect, pixmap=fitz.Pixmap(png), keep_proportion=True)
return document.write()
if __name__ == "__main__":
result = handle(None)
with open("result.pdf", "wb") as file:
file.write(result)
@JorjMcKie
Copy link

hm, works fine on my Windows, but segfaults on Linux ...

@JorjMcKie
Copy link

Jpegs also seem to always work on Linux.
I'll try a PNG on Linux now ...

@JorjMcKie
Copy link

The following also works fine on Windows and Linux. The PNG is a transparent image. Using bytes instead of BytesIO also works in either case.
Something special must be hidden in your case ...

import fitz
import io

pdffile = open("showPDFpage.pdf", "rb")
pdfstream = io.BytesIO(pdffile.read())  # or pdffile.read()
doc = fitz.open("pdf", pdfstream)
page = doc[0]

imgfile = open("test.png", "rb")
imgstream = imgfile.read()  # or io.BytesIO(imgfile.read())

rect = fitz.Rect(100, 400, 300, 700)
page.insertImage(rect, stream=imgstream)
page.drawRect(rect)
doc.save("test-add.pdf")

pdffile.close()
imgfile.close()

@JorjMcKie
Copy link

Your example works always, if you take stream instead of pixmap.

(Not to mention, that the pixmap should be created only once, outside the loop for every page ...)

So there is a problem with specifically pixmap now ...

@svenw3
Copy link

svenw3 commented May 7, 2019

Segfaults on macOS Mojave (10.14.3), too. Stream and filename work.

Reverting to pip install pymupdf==1.14.12 works fine with pixmap, so there is an error introduced in 1.14.13?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment