0

I used PyPDF2 to rotate the pages of several PDFs.

Now, I'm also trying to crop them. However, I've found that the coordinates that I use in mediabox for the new rotated PDFs seem to apply instead to the original orientation. For example, (0,0) is the upper right of the rotated PDFs, instead of in the lower left. Here's my code:

import os
from PyPDF2 import PdfReader, PdfWriter

reader = PdfReader("myfile.pdf")
writer = PdfWriter()
    
for page in reader.pages:
    page.rotate_clockwise(180)
    writer.add_page(page)
        
with open("rotated_myfile.pdf", "wb") as pdf_out:
    writer.write(pdf_out)

# The coordinates seem to still apply to the ORIGINAL orientation
reader = PdfReader("rotated_myfile.pdf")
page = reader.pages[0]

page.mediabox.lower_left = (0, 0)
page.mediabox.lower_right = (300, 0)
page.mediabox.upper_left = (0, 300)
page.mediabox.upper_right = (300, 300)

writer = PdfWriter()
writer.add_page(page)
with open("tmp.pdf", "wb") as pdf_out:
    writer.write(pdf_out)

Obviously I could work out the math myself, but is there a way to do the rotations so that the coordinates correspond to the places on the page where they usually do - like (0,0) being in the lower left?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
Joe
  • 662
  • 1
  • 7
  • 20
  • [this answer](https://stackoverflow.com/a/69078973/6394617) states that "PDF rotation modifies the whole coordinate system rather than just the page, thus PDF boxes always refer to the non-rotated page", so perhaps what I'm asking how to do is not actually possible. – Joe Oct 06 '22 at 13:33

0 Answers0