35

I want to read a PDF and get a list of its pages and the size of each page. I don't need to manipulate it in any way, just read it.

Currently trying out pyPdf and it does everything I need except a way to get page sizes. Understanding that I will probably have to iterate through, as page sizes can vary in a pdf document. Is there another libray/method I can use?

I tried using PIL, some online recipes even have d=Image(imagefilename) usage, but it NEVER reads any of my PDFs - it reads everything else I throw at it - even some things I didn't know PIL could do.

Any guidance appreciated - I'm on windows 7 64, python25 (because I also do GAE stuff), but I'm happy to do it in Linux or more modern pythiis.

1
  • PIL does not (and most probably never will) support PDFs, because they're a very complex kind of vector graphics. PIL focuses on raster images. Working with PDFs is a task for dedicated libraries, such as pikepdf or pymupdf.
    – mara004
    Sep 19, 2021 at 8:10

8 Answers 8

47

This can be done with pypdf:

>>> from pypdf import PdfReader
>>> reader = PdfReader('example.pdf')
>>> box = reader.pages[0].mediabox
>>> box
RectangleObject([0, 0, 612, 792])
>>> box.width
Decimal('612')
>>> box.height
Decimal('792')

(Formerly known as pyPdf / PyPDF2)

2
  • 1
    input1 = PdfFileReader(file('example.pdf', 'rb') works for me this way.
    – bluerubez
    Sep 17, 2015 at 20:23
  • 1
    The coordinate values are called points, where by default 1 point is equivalent to 1/72 of an inch. However, each page can define a custom UserUnit, which is a factor that scales all coordinates.
    – mara004
    Sep 19, 2021 at 8:26
17

With pdfrw:

>>> from pdfrw import PdfReader
>>> pdf = PdfReader('example.pdf')
>>> pdf.pages[0].MediaBox
['0', '0', '595.2756', '841.8898']

Lengths are given in points (1 pt = 1/72 inch). The format is [x0, y0, x1, y1] (thanks, mara004!).

3
  • 3
    "Lengths are given in points" unless the page contains a UserUnit entry which can be used to change the unit here. This option admittedly is used very seldom only.
    – mkl
    May 17, 2018 at 15:58
  • I've tried this, but it failed to extract the information sometime, while PyMuPDF (cges30901's answer) performed well all the time. The reason is that pdfrw failed to extract the "/MediaBox" key from the pdf file sometime (wierd).
    – Dzhuang
    Jan 20, 2021 at 4:43
  • 3
    "The format is ['0', '0', width, height]" - This is wrong. The format is [x0, y0, x1, y1]. It does not necessarily need to start with 0.
    – mara004
    Sep 19, 2021 at 7:43
17

Update in 2021-07-22: original answer was not always correct, so I update my answer.

With PyMuPDF:

>>> import fitz
>>> doc = fitz.open("example.pdf")
>>> page = doc[0]
>>> print(page.rect.width, page.rect.height)
842.0 595.0
>>> print(page.mediabox.width, page.mediabox.height)
595.0 842.0

Return values of mediabox and rect are of type Rect, which has attributes "width" and "height". One difference between mediabox and rect is that mediabox is the same as /MediaBox in document and does not change if page is rotated. However, rect is affected by rotation. For more information about different boxes in PyMuPDF, you can read glossary.

8
  • 2
    Instead of doc.loadPage(0) you can also simply write doc[0] :-) Aug 20, 2020 at 9:43
  • page here has also an attribute MediaBoxSize which returns the size.
    – Jboulery
    Aug 20, 2020 at 15:48
  • 2
    This is the fastest wrapper library to read PDF files
    – am.rez
    Oct 11, 2020 at 23:57
  • The CropBox attribute of Page objects returns the unrotated size as a Rect object. That Rect has width and height attributes. This is a quick way to get to the relevant bits.
    – Alex Povel
    Nov 9, 2020 at 10:53
  • 1
    @rain01 Order is not changed, but when a page is rotated 90 or 270 degrees, the number of pixels in a column is actually the real width, and the number of pixels in a row is the real height.
    – cges30901
    Jul 21, 2021 at 11:33
7

for pdfminer python 3.x (pdfminer.six) (did not try on python 2.7):

parser = PDFParser(open(pdfPath, 'rb'))
doc = PDFDocument(parser)
pageSizesList = []
for page in PDFPage.create_pages(doc):
    print(page.mediabox) # <- the media box that is the page size as list of 4 integers x0 y0 x1 y1
    pageSizesList.append(page.mediabox) # <- appending sizes to this list. eventually the pageSizesList will contain list of list corresponding to sizes of each page
3
  • works for me too. also do you know the difference between mediabox and cropbox?
    – ferdynator
    Apr 30, 2018 at 11:05
  • in short, mediabox is the size of the whole page including the white margins. cropbox is the size of the page + any area used by applications to do any functionality. checkout wiki.scribus.net/canvas/…
    – Myonaiz
    May 1, 2018 at 7:02
  • If a cropbox is defined, that's the part of the page a PDF viewer would usually display.
    – mara004
    Sep 19, 2021 at 8:16
6

With pikepdf:

import pikepdf

# open the file and select the first page
pdf = pikepdf.Pdf.open("/path/to/file.pdf")
page = pdf.pages[0]

if '/CropBox' in page:
    # use CropBox if defined since that's what the PDF viewer would usually display
    relevant_box = page.CropBox
elif '/MediaBox' in page:
    relevant_box = page.MediaBox
else:
    # fall back to ANSI A (US Letter) if neither CropBox nor MediaBox are defined
    # unlikely, but possible
    relevant_box = [0, 0, 612, 792]

# actually there could also be a viewer preference ViewArea or ViewClip in
# pdf.Root.ViewerPreferences defining which box to use, but most PDF readers 
# disregard this option anyway

# check whether the page defines a UserUnit
userunit = 1
if '/UserUnit' in page:
    userunit = float(page.UserUnit)

# convert the box coordinates to float and multiply with the UserUnit
relevant_box = [float(x)*userunit for x in relevant_box]

# obtain the dimensions of the box
width  = abs(relevant_box[2] - relevant_box[0])
height = abs(relevant_box[3] - relevant_box[1])

rotation = 0
if '/Rotate' in page:
    rotation = page.Rotate

# if the page is rotated clockwise or counter-clockwise, swap width and height
# (pdf rotation modifies the coordinate system, so the box always refers to 
# the non-rotated page)
if (rotation // 90) % 2 != 0:
    width, height = height, width

# now you have width and height in points
# 1 point is equivalent to 1/72in (1in -> 2.54cm)
0

Another way is to use popplerqt4

doc = popplerqt4.Poppler.Document.load('/path/to/my.pdf')
qsizedoc = doc.page(0).pageSize()
h = qsizedoc.height() # given in pt,  1pt = 1/72 in
w = qsizedoc.width() 
1
0

disclaimer: I am the author of borb, the library used in this answer.

#!chapter_005/src/snippet_002.py
import typing
from borb.pdf import Document
from borb.pdf import PDF


def main():

    # read the Document
    doc: typing.Optional[Document] = None
    with open("output.pdf", "rb") as in_file_handle:
        doc = PDF.loads(in_file_handle)

    # check whether we have read a Document
    assert doc is not None

    # get the width/height
    w = doc.get_page(0).get_page_info().get_width()
    h = doc.get_page(0).get_page_info().get_height()

    # do something with these dimensions
    # TODO

if __name__ == "__main__":
    main()

We start the code by loading the PDF using PDF.loads. Then we get a Page (you could change this code to print the dimensions of each Page, rather than just Page 0). From that Page, we get PageInfo, which contains the width and height.

You can install borb by using pip:

pip install borb

You can also download it from source here.

If you need further examples, check out the examples repository.

-2

Right code for Python 3.9 and library PyPDF2:

from PyPDF2 import PdfFileReader

reader = PdfFileReader('C:\\MyFolder\\111.pdf')
box = reader.pages[0].mediaBox
print(box.getWidth())
print(box.getHeight())

For all pages:

from PyPDF2 import PdfFileReader

reader = PdfFileReader('C:\\MyFolder\\111.pdf')

i = 0
for p in reader.pages:
    box = p.mediaBox
    print(f"i:{i}   page:{i+1}   Width = {box.getWidth()}   Height = {box.getHeight()}")
    i=i+1
    
input("Press Enter to continue...")
1
  • 2023 update: PyPDF2 was merged back into pypdf. Use pypdf. PyPDF2 is deprecated. Mar 23 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy