Search code examples
python-3.xpdfpypdf

Check if page is vertical using PyPDF2?


Is there a way to check to see if a PDF page is vertical using PyPDF2?

Ideally, there would be method pdfReader.getPage(0).isVertical() that returns true or false, but I can't find anything in the PageObject docs

I am attempting to merge a watermark on top of the first page of the a PDF, but it only looks right if the PDF is in vertical orientation.

Was hoping to do the following.

if (not (pdfReader.getPage(0).isVertical())):
    pdfReader.getPage(0).rotateClockwise(90)

Solution

  • I was able to guarantee my first page, firstPage = PyPDF2.PdfFileReader(pdfFile).getPage(0), was vertical by using a combination of a two things.

    Code

    I calculated isVertical by using the coordinates of upper right and lower right.

    def isVertical(page):
        page = page.mediaBox
        return page.getUpperRight_x() - page.getUpperLeft_x() < page.getUpperRight_y() - page.getLowerRight_y()
    

    If the page was landscape, I rotate it by 90 degrees left, this could cause the page to be upside down, but at least it is vertical. If the pdf page is rotated, rotate it back.

    if (not isVertical(firstPage)):
        firstPage.rotateCounterClockwise(90)
    
    if (firstPage.get('/Rotate')):
        firstPage.rotateCounterClockwise(firstPage.get('/Rotate'))