Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract text from pdf in Python 3.7

I am trying to extract text from a PDF file using Python. My main goal is I am trying to create a program that reads a bank statement and extracts its text to update an excel file to easily record monthly spendings. Right now I am focusing just extracting the text from the pdf file but I don't know how to do so.

What is currently the best and easiest way to extract text from a PDF file into a string? What library is best to use today and how can I do it?

I have tried using PyPDF2 but everytime I try to extract text from any page using extractText(), it returns empty strings. I have tried installing textract but I get errors because I need more libraries I think.

import PyPDF2

pdfFileObj = open("January2019.pdf", 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

pageObj = pdfReader.getPage(0)
print(pageObj.extractText())

This prints empty strings when it should be printing the contents of the page

like image 846
RaV1oLLi Avatar asked Apr 19 '19 20:04

RaV1oLLi


People also ask

How do I extract text from a PDF in Python?

Now, we create an object of PageObject class of PyPDF2 module. pdf reader object has function getPage() which takes page number (starting form index 0) as argument and returns the page object. Page object has function extractText() to extract text from the pdf page. At last, we close the pdf file object.

Can you extract data from a PDF with Python?

There are a couple of Python libraries using which you can extract data from PDFs. For example, you can use the PyPDF2 library for extracting text from PDFs where text is in a sequential or formatted manner i.e. in lines or forms. You can also extract tables in PDFs through the Camelot library.

How do I convert a PDF to text in Python?

Step 01 – Create a PDF file (or find an existing one) Open a new Word document. Type in some content of your choice in the word document. Now to File > Print > Save. Remember to save your pdf file in the same location where you save your python script file.


2 Answers

I have tried many methods but failed, include PyPDF2 and Tika. I finally found the module pdfplumber that is work for me, you also can try it.

Hope this will be helpful to you.

import pdfplumber
pdf = pdfplumber.open('pdffile.pdf')
page = pdf.pages[0]
text = page.extract_text()
print(text)
pdf.close()
like image 130
Fly your ideas Avatar answered Sep 20 '22 18:09

Fly your ideas


Using tika worked for me!

from tika import parser

rawText = parser.from_file('January2019.pdf')

rawList = rawText['content'].splitlines()

This made it really easy to extract separate each line in the bank statement into a list.

like image 31
RaV1oLLi Avatar answered Sep 20 '22 18:09

RaV1oLLi