PDF page is mirrored, origin is at bottom-left
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")
The input file is test.pdf. test.pdf
The result is output.pdf.
Any help is appreciated.
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.
Associated MuPDF issue link: https://bugs.ghostscript.com/show_bug.cgi?id=708393
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
Thanks for your excellent response! This helps a lot!
[Reopening until we've made a release with the fix.]
Fixed in PyMuPDF-1.25.5.