How to extract text from a pdf file
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]
- ↑ https://stackoverflow.com/questions/17271319/how-do-i-install-pip-on-macos-or-os-x
- ↑ Need this because error says: This script does not work on Python 2.7 The minimum supported Python version is 3.6. Please use https://bootstrap.pypa.io/pip/2.7/get-pip.py instead.
- ↑ https://stackoverflow.com/questions/60348649/python-version-does-not-update
- ↑ https://macpaw.com/how-to/get-file-path-mac
- ↑ https://www.maketecheasier.com/run-python-script-in-mac/
- ↑ https://stackoverflow.com/questions/39241643/no-module-named-pypdf2-error
- ↑ https://stackoverflow.com/questions/34837707/how-to-extract-text-from-a-pdf-file
- ↑ https://stackoverflow.com/questions/55608376/pypdf2-extract-empty-text-python3