15

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 pages[i].extract_text() functionality in pypdf. Does anyone know how to extract text per page using pdfMiner?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958

2 Answers2

15
for pageNumber, page in enumerate(PDFDocument.get_pages()):
    if pageNumber == 42:
        #do something with the page

There is a pretty good article here.

John
  • 13,197
  • 7
  • 51
  • 101
  • 3
    Could 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
  • E AttributeError: type object 'PDFDocument' has no attribute 'get_pages' – Joey Baruch Jun 20 '23 at 20:49
  • @JoeyBaruch It looks like that method was removed since this answer was written. There is an example here on how to use pdfminer.six that should work instead of this answer. https://pdfminersix.readthedocs.io/en/latest/tutorial/composable.html – John Jun 21 '23 at 22:50
11

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
  • 487
  • 1
  • 5
  • 13
  • 1
    It should be io.BytesIO() instead of io.StringIO() for uni-code characters. Everything else works great. :) – Nyambaa Aug 28 '19 at 09:19