PyMuPDF | inserted image is in the wrong place of a pdf page

Question:

I need to insert an image into some pages of a pdf and I use insertImage. Following the example I provide fitz.Rect(0, 0, 50, 50) as I want to place the image in the top left corner of the page. Works perfectly for all pdfs, but one – a scanned document for which the image appears somewhere in the center of the page and the image is also 90 rotated. What might cause the difference in the result for that particular pdf and how can I solve it?

Asked By: Mihail Panayotov

||

Answers:

According to PyMuPDF documentation here, due to inconsistencies in how the PDF was created, it is possible the origin of that particular document is not the standard global origin on top-left.

The following snippet resets the geometry of the page:

if not(page._isWrapped):
    page._wrapContents()

If this workaround doesn’t work the best, there are other potential solutions listed on the site.

Answered By: willing_astronomer

I test with Python 3.7.3; PyMuPDF 1.20.2
no need to check page._isWrapped, ( actuall it will show:
AttributeError: ‘Page’ object has no attribute ‘_isWrapped’
)

only the below lines is enough:

import fitz

def test_func():
    doc = fitz.open('test.pdf')
    for page in doc:
        page.wrap_contents()
        # do some other stuff
    doc.save('test-new.pdf')
Answered By: Michael Hou
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.