I have experimented with both pyPdf and pdfMiner to extract text from pdf files. I have some unfriendly pdfs that only pdfMiner is able to extract successfully. I am using the code here to extract text for the entire file. However, I would really like to extract text on a per page basis like the getPage(i).extractText() functionality in pyPdf. Does anyone know how to extract text per page using pdfMiner?
Asked
Active
Viewed 2.4k times
14
Community
- 1
- 1
2 Answers
13
for pageNumber, page in enumerate(PDFDocument.get_pages()):
if pageNumber == 42:
#do something with the page
There is a pretty good article here.
John
- 12,723
- 7
- 48
- 99
-
3Could somebody elaborate on this? I'm having significant trouble getting my head around pdfminer as there is no documentation at all. – Jazcash Jan 14 '14 at 12:24
-
for which version of `pdfminer` does this code work? – Rohan Amrute Jan 04 '16 at 11:11
-
This would appear to broken with the current *pdfminer* (the time of writing of writing 20140328). – Att Righ Mar 28 '17 at 17:24
9
This is how you write all the pages to separate files:
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfparser import PDFParser
import io
import os
fp = open('Files/Company_list/0010/pdf_files/testfile3.pdf', 'rb')
rsrcmgr = PDFResourceManager()
retstr = io.StringIO()
print(type(retstr))
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
page_no = 0
for pageNumber, page in enumerate(PDFPage.get_pages(fp)):
if pageNumber == page_no:
interpreter.process_page(page)
data = retstr.getvalue()
with open(os.path.join('Files/Company_list/0010/text_parsed/2017AR', f'pdf page {page_no}.txt'), 'wb') as file:
file.write(data.encode('utf-8'))
data = ''
retstr.truncate(0)
retstr.seek(0)
page_no += 1
Just replace page_no with page number you want if you want specific page numbers.
TheProgramMAN123
- 447
- 1
- 5
- 12
-
1It should be io.BytesIO() instead of io.StringIO() for uni-code characters. Everything else works great. :) – Nyambaa Aug 28 '19 at 09:19