Python – How to extract text from a PDF file


I'm trying to extract the text included in this PDF file using Python.

I'm using the PyPDF2 module, and have the following script:

import PyPDF2
pdf_file = open('sample.pdf')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(0)
page_content = page.extractText()
print page_content

When I run the code, I get the following output which is different from that included in the PDF document:


How can I extract the text as is in the PDF document?

Best Solution

I was looking for a simple solution to use for python 3.x and windows. There doesn't seem to be support from textract, which is unfortunate, but if you are looking for a simple solution for windows/python 3 checkout the tika package, really straight forward for reading pdfs.

Tika-Python is a Python binding to the Apache Tika™ REST services allowing Tika to be called natively in the Python community.

from tika import parser # pip install tika

raw = parser.from_file('sample.pdf')

Note that Tika is written in Java so you will need a Java runtime installed