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())