使用 Python PyPDF2 从扫描的 pdf(图像)中提取文本

Mou*_*a K 1 python pypdf python-imaging-library data-extraction

我一直在尝试从扫描的 PDF(带有不可选择文本的图像)中提取文本。

但是,我得到的输出不是人类可读的。

我想要包含 pdf 链接中的日期、发票号的信息(https://drive.google.com/file/d/1qQsqhlSKTZs-hlswrV8PIirR36896KXZ/view)。

请帮助我以纯文本形式提取和存储相同的内容。

import PyPDF2
from PIL import Image
pdf_reader = PyPDF2.PdfFileReader(r'document.pdf', 'rb')
page = pdf_reader.getPage(85)
if '/XObject' in page['/Resources']:
    xobject = page['/Resources']['/XObject'].getObject()
    for obj in xobject:
        if xobject[obj]['/Subtype'] == '/Image':
            size = (xobject[obj]['/Width'], xobject[obj]['/Height'])
            data = xobject[obj]._data
            print("*******", data)
            print(xobject[obj]['/Filter'])
Run Code Online (Sandbox Code Playgroud)

Kar*_*Żak 9

[更新]
我不认为 PyPDF2 可以从图像中读取文本...
要将图像转换为文本,我建议使用一些 OCR 工具,例如PyTesseract这是一个使用pdf2image和 PyTesseract 来实现您正在寻找的内容的
示例(您需要首先正确安装 PyTesseract/Tesseract 和 pdf2image):

import pdf2image
import pytesseract
from pytesseract import Output, TesseractError

pdf_path = "document.pdf"

images = pdf2image.convert_from_path(pdf_path)

pil_im = images[0] # assuming that we're interested in the first page only

ocr_dict = pytesseract.image_to_data(pil_im, lang='eng', output_type=Output.DICT)
# ocr_dict now holds all the OCR info including text and location on the image

text = " ".join(ocr_dict['text'])
Run Code Online (Sandbox Code Playgroud)