首页 > 解决方案 > 使用 pdfminer.six 从每个 PDF 页面中提取文本

问题描述

pdfminer 的文档充其量是很差的。我最初使用 pdfminer 并让它适用于一些 PDF 文件,然后我遇到了一些错误并意识到我应该使用 pdfminer.six

我想从 PDF 的每一页中提取文本,这样我就可以密切关注我在哪里找到了特定的单词等。

使用文档:

from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice

# Open a PDF file.
fp = open('mypdf.pdf', 'rb')
# Create a PDF parser object associated with the file object.
parser = PDFParser(fp)
# Create a PDF document object that stores the document structure.
# Supply the password for initialization.
document = PDFDocument(parser, password)
# Check if the document allows text extraction. If not, abort.
if not document.is_extractable:
    raise PDFTextExtractionNotAllowed
# Create a PDF resource manager object that stores shared resources.
rsrcmgr = PDFResourceManager()
# Create a PDF device object.
device = PDFDevice(rsrcmgr)
# Create a PDF interpreter object.
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Process each page contained in the document.
for page in PDFPage.create_pages(document):
    interpreter.process_page(page)

我们已经解析了所有页面,但没有关于如何从 PDFpage 获取哪些元素或任何内容的文档

我查看了 PDFPage.py 文件,寻找一种从每个 PDF 页面中提取文本的方法,当然这并不是那么简单。

更复杂的是,至少有 3 个版本的 pdfminer,当然随着时间的推移,事情已经升级,所以我能找到的任何示例都不兼容。

标签: pythonparsingpdfpdfminer

解决方案


这是我用于从 pdf 文件中提取文本的版本。

import io
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage


def extract_text_from_pdf(pdf_path):
    """
    This function extracts text from pdf file and return text as string.
    :param pdf_path: path to pdf file.
    :return: text string containing text of pdf.
    """
    resource_manager = PDFResourceManager()
    fake_file_handle = io.StringIO()
    converter = TextConverter(resource_manager, fake_file_handle)
    page_interpreter = PDFPageInterpreter(resource_manager, converter)

    with open(pdf_path, 'rb') as fh:
        for page in PDFPage.get_pages(fh, caching=True, check_extractable=True):
            page_interpreter.process_page(page)

        text = fake_file_handle.getvalue()

    # close open handles
    converter.close()
    fake_file_handle.close()

    if text:
        return text
    return None

推荐阅读