Python PDF Processing

Python PDF Processing

Python can read PDF files, extract text from them, and then print the contents. To do this, we first need to install the required module, PyPDF2. Below are the commands to install this module. Pip should already be installed in your Python environment.

pip install pypdf2

Once installed, we can use the methods available in 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 the page number for each, we use a loop with the getPageNumber() function. In the example below, we have a PDF file with two pages. The content will be printed under two separate page headings. </p>
<pre><code class="language-python line-numbers">import PyPDF2

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

for i in xrange(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 we run 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 p
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 *