How do I properly insert text into a rotating page? #3366
-
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
Please provide enough information to reproduce. |
Beta Was this translation helpful? Give feedback.
-
In the general case, you need the page's rotation matrix and the rotation value. Then, for every insertion point |
Beta Was this translation helpful? Give feedback.
-
Sorry for reopening the post, but I encountered the same issue as OP and was not able to solve it so far. I have a scanned PDF (images only; rotation 270) and a text layer PDF (coming from tesseract, rotation 0). I want to merge these two PDFs into a single PDF but every attempt ended up in one of the PDFs incorrectly rotated. I tried page.set_rotation() for both image page and text page before merging them into a new page, I tried Matrix.prerotate() as well to no avail. This is my code: import fitz
# prepare original page
original = fitz.open("image_pdf.pdf")
original_page = original[0]
text_doc = fitz.open("text_page.pdf")
text_page = text_doc[0]
page_width = original_page.rect.width
page_height = original_page.rect.height
rotation = original_page.rotation
rotation_text = text_page.rotation
print(f"Rotation Original: {rotation}")
print(f"Rotation Text: {rotation_text}")
new_doc = fitz.open()
# # Handle rotation
if rotation in [90, 270]:
# flip width and height
page_width, page_height = page_height, page_width
new_page = new_doc.new_page(width=original_page.rect.height, height=original_page.rect.width)
# calculate scaling factors
scale_x = page_width / original_page.rect.width
scale_y = page_height / original_page.rect.height
# Adjust for rotation
if rotation != 0:
# rotate the new page back to match the original page
new_page.set_rotation(rotation)
# Create a transformation matrix for scaling
transform = fitz.Matrix(scale_x, scale_y)
# Render the text page onto the original page
new_page.show_pdf_page(new_page.rect, original, 0, matrix=transform)
new_page.show_pdf_page(new_page.rect, text_doc, 0, matrix=transform)
# Save the new document as a PDF
new_doc.save("image_page.pdf") As I understood from your conversation above, we could use I would appreciate so much if you could point me to the right direction. |
Beta Was this translation helpful? Give feedback.
-
The simplest way to achieve what you want is to forget all about rotation by removing any source page rotation via This page method can always be executed - even when the rotation already is 0. |
Beta Was this translation helpful? Give feedback.
In the general case, you need the page's rotation matrix and the rotation value. Then, for every insertion point
origin
dopage.insert_text(origin * page.derotation_matrix, "text", rotate=angle)
.