How to extract text from a pdf file

From Secure OS Wiki
Jump to navigation Jump to search

Youtube video reference here. This tutorial is done on a Mac laptop.

1. In terminal:

   curl https://bootstrap.pypa.io/pip/2.7/get-pip.py -o get-pip.py[1][2]
   python get-pip.py
   python -m pip install pyPDF2 [3]

2. In python editor (Sublime Text):

   from pyPDF2 import PdfFileReader, PdfFileWriter

Save the file as demo.py. Go to File > Save. Write down demo.py.

3. You may need to find the location of the pdf file you have stored.[4] To find the file go to Finder and search for the filename. Right click (or ctrl+click) the file, then press and hold option, then click "Copy "<file name here>" as Pathname". Doing so will copy to the clipboard the file name. Let go of option. Now you can right click and select paste (or Command+V) to write down the file path. If the pdf file is in the same folder as the python editor file (demo.py), you can proceed as follows.

4. In python editor: In my case, my pdf file name is Aetna2021-08-04_3371.03EOB.pdf, so I have

   file_path='Aetna2021-08-04_3371.03EOB.pdf'

then write (naming the file you are writing to e.g. <name here>_Notes.txt):

   pdf=PdfFileReader(file_path)
       with open('Aetna2021-08-04_3371.03EOB_Notes.txt', 'w') as f:
           for page_num in range(pdf.numPages):
               print('Page): {0}'.format(page_num))
               pageObj = pdf.getPage(page_num)
   
               try:
                   txt = pageObj.extractText()
                   print(,center(100, '-'))
               except:
                   pass
               else:
                   f.write('Page {0}\n'.format(page_num+1))
                   f.write(.center(100,'-'))
                   f.write(txt)
           f.close()

5. Then run the script.[5] Open terminal. Find the demo.py file in finder. In terminal write

   cd

Then, drag the file to terminal. Erase demo.py part of path and press enter. You're entering, for example:

   cd /Users/weiqihu/Documents/Heena\ Automation/demo.py

In terminal:

   python demo.py

You may need to install some developer tools at this point. Could take 4 minutes.

Troubleshooting[edit | edit source]

1. You may get an error in step 5 if you use python3 demo.py instead of python demo.py.[6]

2. Trying this code with a couple pdf files yields blank .txt files. I can also use another module.[7][8]

References[edit | edit source]