'PDF FILE ORIENTATION detection

I need a help to detect a orientation of a PDF file (Portrait or Landscape) by using Python. anyone has an idea?

I have been trying different libs but not successful yet.



Solution 1:[1]

Each page can be in a different orientation, but you can use PyPDF to detect the page size of the first page and determine the orientation accordingly:

from PyPDF2  import PdfFileReader

pdf = PdfFileReader(file('example.pdf'))
page = pdf.getPage(0).mediaBox
if page.getUpperRight_x() - page.getUpperLeft_x() > page.getUpperRight_y() - page.getLowerRight_y():
    print('Landscape')
else:
    print('Portrait')

Solution 2:[2]

It is not necessary to calculate the size

from fpdf import FPDF
pdf = PdfReader('example.pdf')
page = pdf.getPage(1)
if page.MediaBox[3] > page.MediaBox[4]:
    print('P')
else:
    print('L')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joe Hildebrand
Solution 2 Cristian Festi