Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 680
Henry Avatar asked Mar 21 '17 15:03

Henry


People also ask

What is difference between PyPDF2 and PyPDF4?

There was a brief series of releases of a package called PyPDF3 , and then the project was renamed to PyPDF4 . All of these projects do pretty much the same thing, but the biggest difference between pyPdf and PyPDF2+ is that the latter versions added Python 3 support.

What does PyPDF2 do?

PyPDF2 is a Python library that allows the manipulation of PDF documents. It can be used to create new PDF documents, modify existing ones and extract content from documents. PyPDF2 is a pure Python library that requires no non-standard modules.


1 Answers

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'))
like image 83
Henry Avatar answered Oct 04 '22 17:10

Henry