For any queries you can reach us at / WhatsApp us: +919158876092

PDF Text Extraction using Python

PDF text extraction using Python

In this tutorial, you will learn how to extract text from a given PDF in Python. We will be using the PyPDF2 module for exctracting the text from PDF files.

Installing the module

To install the PyPDF2 module and some other related dependencies, we can use the pip command:

pip install pypdf2

The Details

For extracting text from a PDF file we will be using the PdfFileReader class which is usd to initialize PdfFileReader object, taking a stream parameter, in which we will provide the file stream for the PDF file.

The Code (

from PyPDF2 import PdfFileReader

# opening the pdf file in binary ready mode
file = open("sample.pdf", "rb")

# instantiate the object
reader = PdfFileReader(file)

print(f"Printing the document info: {reader.getDocumentInfo()}")


# get number of pages of the document
print(f"Number of Pages: {reader.getNumPages()}")

print(f"PDF file created By: {reader.getDocumentInfo().creator}")


pages = reader.getNumPages()

for i in range(0, pages):
    print(f"Page Number: {i+1}")
    pageObj = reader.getPage(i)

# close the pdf file object

Other applications of PyPDF2 Module

  • Rotating a PDF file page by any defined angle.
  • Merging two or more PDF files at a defined page number
  • Appending two or more PDF files, one after another.
  • Find all the meta information for any PDF, like creator, author, date of creation etc.
  • We can even create a new PDF file using the text coming from some text file.