Strange coordinates and size of newly inserted images #2494
-
In some pdf document the coordinates of a new inserted image via Page.insert_image() function are very strange.
Output:
LINK TO THE PDF: pdf link EDIT: I could not find a way to move the already inserted image via PyMuPDF (hundreds of pdfs), found no examples or explanation. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
This question has been answered in the associated issue #2495. |
Beta Was this translation helpful? Give feedback.
-
Test 1: In [1]: import fitz
In [2]: doc=fitz.open("bad stamp example.pdf")
In [3]: page=doc[0]
In [4]: page.wrap_contents()
In [5]: xref = page.insert_image((0, 0, 400, 200), filename="nur-ruhig.png")
In [6]: # save PDF to memory and re-open:
In [7]: pdfdata = doc.tobytes(deflate=True)
In [8]: doc.close()
In [9]: doc = fitz.open("pdf", pdfdata)
In [10]: page = doc[0]
In [11]: page.get_image_rects(xref)
Out[11]: [Rect(112.375244140625, 0.0, 287.624755859375, 200.0)]
In [12]: # PERFECT!!! |
Beta Was this translation helpful? Give feedback.
-
I suggest you use the following script. It should able to cope with all or most peculiar input files (rotated pages, weird geometries, weird MediaBox / CropBox and what not). import fitz
doc = fitz.open() # new output file
src = fitz.open("2.pdf") # source file
imgfile = "nur-ruhig.png"
for src_page in src: # iterate over input pages
src_rect = src_page.rect # source page rect
w, h = src_rect.br # save its width, height
src_rot = src_page.rotation # save source rotation
src_page.set_rotation(0) # set rotation to 0 temporarily
page = doc.new_page(width=w, height=h) # make output page
page.show_pdf_page( # insert source page
page.rect,
src,
src_page.number,
rotate=-src_rot, # use reversed original rotation
)
page.insert_image((0, 0, 400, 200), filename=imgfile)
doc.ez_save("output.pdf") Every output page will have rotation 0 and all images shold be inserted as expected. |
Beta Was this translation helpful? Give feedback.
Test 1: