Python – Processing PDFs

Python – PDF Processing

Python can read PDF files and extract text content from them for output. To do this, we must first install the required module, PyPDF2. Below are the commands to install this module. You should already have pip installed in your Python environment.

pip install pypdf2

Once this module is successfully installed, we can use the methods available within the module to read PDF files.

import PyPDF2

pdfName = 'pathTutorialspoint.pdf'
read_pdf = PyPDF2.PdfFileReader(pdfName)
page = read_pdf.getPage(0)
page_content = page.extractText()
print(page_content)

When running the above program we get the following output −

Tutorials Point originated from the idea that there exists a class of readers who respond better
to online content and prefer to learn new skills at their own pace from the comforts of their
drawing rooms.

The journey commenced with a single tutorial on </pre>
<h2>Reading Multiple Pages</h2>
<p>To read a PDF with multiple pages and print out each page with its page number, we use a loop and the <code>getPageNumber() function. In the following example, we use a PDF file with two pages. The content is printed with two separate page headers. 

import PyPDF2

pdfName = 'PathTutorialspoint2.pdf'
read_pdf = PyPDF2.PdfFileReader(pdfName)

for i in range(read_pdf.getNumPages()):
    page = read_pdf.getPage(i)
    print('Page No - ' + str(1+read_pdf.getPageNumber(page)))
    page_content = page.extractText()
    print(page_content)

When running the above program we get the following output −

Page No - 1
Tutorials Point originated from the idea that there exists a class of readers who respond better to
online content and prefer to learn new skills at their own pace from the comforts of their drawing
rooms.


Page No-2

The journey commenced with a single tutorial on HTML in 2006 and elated by the response it
generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts
a wealth of tutorials and allied articles on topics ranging from programming languages to the web
designing to academics and much more.

Leave a Reply

Your email address will not be published. Required fields are marked *