python - 使用 pdfminer.6 从每个 PDF 页面中提取文本

标签 python parsing pdf pdfminer

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)

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

我查看了 PDFPage.py 文件,寻找从每个 PDF 页面提取文本的方法,当然事情没那么简单。

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

最佳答案

这是我用于从 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

关于python - 使用 pdfminer.6 从每个 PDF 页面中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52506043/

相关文章:

Python3 & Opencv3 & Multiprocessing 引发系统错误

Python Pandas - Json 到 DataFrame

javascript - 使用 pdfmake 在段落周围添加边框

Python - 动态调用模块中的函数

eclipse - xtext 处理左递归语法

ios - 如何获取 XML 元素并存储它? objective-c

java - 提取字符串中的整数部分

javascript - Adobe PDF Forms Javascript,不同字段的求和值

java - PDF Signing,生成的PDF文档认证无效? (使用外部签名、web-eid、HSM)

python - 无法在循环中不断更改 tkinter 标签文本