python处理pdf文件

PDFMiner API:http://www.unixuser.org/~euske/python/pdfminer/

GitHub:https://github.com/euske/pdfminer

安装方法:pip install pdfminer.six(安装2和3两个版本的python要区分开,用pip3 install pdfminer.six,2不支持pdfminer.six)

推荐使用PDFMiner,简单易懂

这里有几点要注意

我在做pdf处理的时候是要把文字下面有横线的文字替换掉,刚开始以为文字的下划线,所以循环遍历出LTTextBoxHorizontal中每个文字的对象,在对象中找是否有下划线这个属性,但是只有文字的颜色和字体的属性,所以卡住了很久。

但是后面自己做了一个pdf文档,发现下划线时被单独区分的,被保存成了LTRect对象。

但是我用测试文档处理的时候却没有LTRect这个属性,只有LTLine对象,然后就去对比测试文档中的横线和自己做的文档中的下划线,发现测试文档中的并不是文字的下划线,而是生成pdf文档后,后期用别的工具加上去的。

所以,区分文档中对象的属性是需要注意的。

 

下面附上LTTextBoxHorizontal对象的代码:

# -*- coding: utf-8 -*-   
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
from pdfminer.layout import *
from pdfminer.converter import PDFPageAggregator

import os
import pdb

def decode_text(s):
    """
    Decodes a PDFDocEncoding string to Unicode.
    Adds py3 compatability to pdfminer's version.
    """
    if type(s) == bytes and s.startswith(b'\xfe\xff'):
        return six.text_type(s[2:], 'utf-16be', 'ignore')
    else:
        ords = (ord(c) if type(c) == str else c for c in s)
        return ''.join(PDFDocEncoding[o] for o in ords)


fp = open('345.pdf', 'rb')
#来创建一个pdf文档分析器
parser = PDFParser(fp)  
#创建一个PDF文档对象存储文档结构
document = PDFDocument(parser)
# 检查文件是否允许文本提取
if not document.is_extractable:
    raise PDFTextExtractionNotAllowed
else:
    # 创建一个PDF资源管理器对象来存储共赏资源
    rsrcmgr=PDFResourceManager()
    # 设定参数进行分析
    laparams=LAParams()
    # 创建一个PDF设备对象
    # device=PDFDevice(rsrcmgr)
    device=PDFPageAggregator(rsrcmgr,laparams=laparams)
    # 创建一个PDF解释器对象
    interpreter=PDFPageInterpreter(rsrcmgr,device)

    # 处理每一页
    for page in PDFPage.create_pages(document):

        interpreter.process_page(page)

        # 接受该页面的LTPage对象
        layout=device.get_result()

        for x in layout:
            if(isinstance(x,LTTextBoxHorizontal)):
                print(x.get_text())

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

theSmallTears

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值