PyMuPDF icon indicating copy to clipboard operation
PyMuPDF copied to clipboard

PDF page is mirrored, origin is at bottom-left

Open perkma opened this issue 1 year ago • 6 comments

Maybe someone can tell me, why the attached PDF-file is mirrored along the horizontal axis and the origin is bottom right. The rotation is 0 and the rotation matrix is the identity-matrix. The PDF is exported from software Rhino and I can not figure out where this transformation comes from. I know that the problem is related to the PDF file. If I use files from other sources than Rhino everything works fine.

I used the code from issue #4378 to add some text at top left position:

import pymupdf

# code from https://github.com/pymupdf/PyMuPDF/issues/4378

doc = pymupdf.open("test.pdf")
page = doc[0]
rot = page.rotation
orig = pymupdf.Point(100, 100)  # apparent insertion point
text = "Text at Top-Left"
mrot = page.derotation_matrix  # matrix anihilating page rotation
page.insert_text(orig * mrot, text, fontsize=60, rotate=rot)
doc.ez_save("output.pdf")

Image

The input file is test.pdf. test.pdf

The result is output.pdf.

output.pdf

Any help is appreciated.

perkma avatar Mar 28 '25 09:03 perkma

This problem has nothing to do with rotation. Since a long time now (v. 1.23.4, I think), PyMuPDF depends on MuPDF correctly detection the balance of stack / unstack PDF graphics operators ("q" / "Q"). Depending on the resulting of that MuPDF function, the necessary additional "q" or "Q" operators are prepended, respectively appended the a page's /Contents stream. In this case however, the information returned by MuPDF is incorrect (in essence saying: "no problem, go ahead"), while in reality we should have appended a "Q" before our insertion.

I will forward this issue to MuPDF's bug report system.

JorjMcKie avatar Mar 28 '25 13:03 JorjMcKie

Associated MuPDF issue link: https://bugs.ghostscript.com/show_bug.cgi?id=708393

JorjMcKie avatar Mar 28 '25 14:03 JorjMcKie

Confirming correct functioning of the fix using this snippet:

import pymupdf

doc = pymupdf.open("test.pdf")
page = doc[0]
text = "Hello World"
print(page.is_wrapped)  # Check if the page is wrapped
page.insert_text((100, 100), text)
page = doc.reload_page(page)  # Reload the page to ensure the changes are applied
print(page.search_for(text))  # Search for the text to verify it was inserted correctly

Output without the fix (esp. see wrong True response)

True
[Rect(100.0, 738.3909912109375, 156.8369903564453, 753.5050048828125)]

After the fix applied:

False
[Rect(100.0, 88.17500305175781, 156.8369903564453, 103.28900146484375)]

Configuration info: MuPDF commit a9f6fc77d794f1cefac811c6e73c3352dfa5750b

JorjMcKie avatar Mar 29 '25 16:03 JorjMcKie

Thanks for your excellent response! This helps a lot!

perkma avatar Mar 31 '25 05:03 perkma

[Reopening until we've made a release with the fix.]

Fixed in PyMuPDF-1.25.5.