Python提取PDF中的文字和图片

一,使用Python提取PDF中的文字

# 只能处理包含文本的PDF文件
#coding=utf-8
import sys
import importlib
importlib.reload(sys)
from pdfminer.pdfparser import PDFParser,PDFDocument
from pdfminer.pdfinterp import PDFResourceManager,PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal,LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed


def ReadPDF(SourceFilePath,ToFilePath):
    # 以二进制形式打开PDF文件
    FileObj = open(SourceFilePath,"rb")
    # 创建一个PDF文档分析器
    Parser = PDFParser(FileObj)

    # 创建PDF文档
    PDFFile = PDFDocument()

    # 链接分析器与文档对象
    Parser.set_document(PDFFile)
    PDFFile.set_parser(Parser)
    # 提供初始化密码
    PDFFile.initialize()
    # 检测文档是否提供txt转换
    if not PDFFile.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        # 解析数据

        # 数据管理器
        Manager = PDFResourceManager()
        # 创建一个PDF设备对象
        Laparams = LAParams()
        device = PDFPageAggregator(Manager,laparams = Laparams)
        # 创建解释器对象
        Interpreter = PDFPageInterpreter(Manager,device)
        # 开始循环处理,每次处理一页
        for Page in PDFFile.get_pages():
            Interpreter.process_page(Page)
            Layout = device.get_result()
            for x in Layout:
                if (isinstance(x,LTTextBoxHorizontal)):
                    with open(ToFilePath,'a') as ToFileObj:
                        FileInfo = x.get_text()
                        print(FileInfo)
                        ToFileObj.write(FileInfo)

SourceFilePath = "民法典.pdf"
ToFilePath = "test.txt"
ReadPDF(SourceFilePath,ToFilePath)

二,使用Python提取PDF中的图片

#coding=utf-8
import fitz
import time
import re
import os
def pdf2pic(path, pic_path):
    t0 = time.time()                          # 生成图片初始时间
    checkXO = r"/Type(?= */XObject)"           # 使用正则表达式来查找图片
    checkIM = r"/Subtype(?= */Image)"
    doc = fitz.open(path)                      # 打开pdf文件
    imgcount = 0                               # 图片计数
    lenXREF = doc._getXrefLength()             # 获取对象数量长度

    # 打印PDF的信息
    print("文件名:{}, 页数: {}, 对象: {}".format(path, len(doc), lenXREF - 1))

    # 遍历每一个对象
    for i in range(1, lenXREF):
        text = doc._getXrefString(i)            # 定义对象字符串
        isXObject = re.search(checkXO, text)    # 使用正则表达式查看是否是对象
        isImage = re.search(checkIM, text)      # 使用正则表达式查看是否是图片
        if not isXObject or not isImage:        # 如果不是对象也不是图片,则continue
            continue
        imgcount += 1
        pix = fitz.Pixmap(doc, i)               # 生成图像对象
        new_name = "图片{}.png".format(imgcount) # 生成图片的名称
        if pix.n < 5:                           # 如果pix.n<5,可以直接存为PNG
            pix.writePNG(os.path.join(pic_path, new_name))
        else:                                   # 否则先转换CMYK
            pix0 = fitz.Pixmap(fitz.csRGB, pix)
            pix0.writePNG(os.path.join(pic_path, new_name))
            pix0 = None
        pix = None                              # 释放资源
        t1 = time.time()                       # 图片完成时间
        print("运行时间:{}s".format(t1 - t0))
        print("提取了{}张图片".format(imgcount))

if __name__=='__main__':
    path = r"开通Carplay教程.pdf"
    pic_path = os.getcwd()+"\\图片"
    # 创建保存图片的文件夹
    if os.path.exists(pic_path):
        print("文件夹已存在,不必重新创建!")
        pass
    else:
        os.mkdir(pic_path)
    pdf2pic(path, pic_path)

需要注意的是,fitz 模块需要 Microsoft Visual C++ 14版本支持,因此还需要安装此软件,放上此软件的下载地址

https://wws.lanzous.com/b01tsod7i 
密码:gkbi

之后运行时还会报错,ModuleNotFoundError: No module named ‘frontend’,此时需要执行命令

pip install PyMuPDF

代码即可运行

猜你喜欢

转载自blog.csdn.net/zhuan_long/article/details/111287940