利用Python将PDF转html并提取文字和图片

由于工作项目中所需要做一个提取pdf中内容和图片的功能,在使用过的几种方法中,还原度高的只有pdf2htmlEX,但pdf2htmlEX在项目中的用处不到,我们用更简单的方法实现

利用Python将PDF转html并提取文字和图片

由于工作项目中所需要做一个提取pdf中内容和图片的功能,在使用过的几种方法中,还原度高的只有pdf2htmlEX,但pdf2htmlEX在项目中的用处不到,我们用更简单的方法实现

1、安装相关python库
pip install PyMuPDF
pip install tqdm
pip install Beautifulsoup4
2、代码实现
import fitz
import os,re,io
from tqdm import tqdm
import base64
from bs4 import BeautifulSoup
from PIL import Image

def decode_image(src, dir, index):

    # 1、信息提取
    result = re.search("data:image/(?P<ext>.*?);base64,(?P<data>.*)", src, re.DOTALL)
    if result:
        ext = result.groupdict().get("ext")
        data = result.groupdict().get("data")
    else:
        raise Exception("Do not parse!")

    imgdata = base64.b64decode(data)
    im = Image.open(io.BytesIO(imgdata))
    width, height = im.size

    print("width:{},height:{}".format(width, height))

    # 2、base64解码
    img = base64.urlsafe_b64decode(data)

    path = dir.replace('.pdf', '')
    if not os.path.exists(path):
        os.makedirs(path, 777)
    # 3、二进制文件保存
    filename = "{}{}.{}".format(path+'/', index, ext)
    print(filename)
    with open(filename, "wb") as f:
        f.write(img)
        f.close()
        
    # 人脸识别使用
    if width % 4 != 0:
        print('resize_4_pic:{}'.format(filename))
        nw = (width % 4 == 0) and width or (width + (4 - (width % 4)))
        nh = (height % 4 == 0) and height or (height + (4 - (height % 4)))

        img = Image.open(filename)
        img = img.resize( (nw,nh), Image.ANTIALIAS)
        img.save(filename)

    imgs.append(filename)
    return filename

def read_pdf(srcfile):
    doc = fitz.open(srcfile)
    html_content = ''
    for page in tqdm(doc):
        html_content += page.get_text('html')

    html_content = html_content.replace('<br/>', ' \n').replace('<br>', ' \n').replace('<br >', ' \n').replace('<br />', ' \n')
    html_content = html_content.replace(' ', ' ').replace('&#160;', ' ')

    soup =  BeautifulSoup(html_content,'lxml')

    index = 0
    for imgtag in soup.find_all('img'):
        decode_image(imgtag['src'], srcfile, index)
        index += 1

    return soup.text

if __name__ == '__main__':
    path = "D:/test.pdf"
    imgs = []
    content = read_pdf(path)
    print(content)
    print(imgs)
上一篇:面向对象三大特性五大原则 + 低耦合高内聚[转载] 下一篇:php项目中调用python脚本使用pdf和image之间相互转换

评论

评论(0)

暂无评论