最近有个需求,需要读取PDF文件中的二维码图片及部分文本,首先想到的是使用Python。
Life is short, I use Python.
经过一番搜索,找到以下库:
库很多,各有各的特长,也各有各的坑!
pdfminer
特性
- 支持Python 3.6及以上版本
- 支持PDF-1.7
- 获取文本位置及其它信息(如字体等)
- 转换PDF为其它格式(HTML/XML)
- 提取提纲、标签数据
- 支持基本加密方式(RC4 and AES)
- 支持多种字体类型(Type1, TrueType, Type3, and CID)
安装
用法
pdf2txt.py
该命令用于提取所有文本,以及文本位置、字体名称、大小、字体方向(横、竖)
1
|
pdf2txt.py samples/simple.pdf
|
dumppdf.py
该命令用于调试pdf,以XML格式打印所有内容
1
|
dumppdf.py samples/simple.pdf
|
pdfminer.six
特性
- pdfminer的所有特性
- 支持解析图片(JPG, JBIG2 and Bitmaps)
- 支持解析表格
安装
1
|
pip install pdfminer.six
|
用法
1
|
pdf2txt.py samples/simple.pdf
|
PyPDF2
安装
用法
1
2
3
4
5
6
7
8
9
10
11
12
|
import PyPDF2
pdfFileObj = open('/path/example.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# 获取PDF总页数
print(pdfReader.numPages)
# 第一页
pageObj = pdfReader.getPage(0)
print(pageObj.extractText())
|
tabula-py
安装
用法
1
2
3
4
5
|
import tabula
# read_pdf 将pdf表格数据存储为Pandas的Dataframe数据类型
df = tabula.read_pdf("/path/table.pdf")
# 打印表格前5行
df.head()
|
如果pdf文件有多个表格
1
|
df = tabula.read_pdf(“offense.pdf”, multiple_tables=True)
|
以JSON格式输出
1
|
tabula.read_pdf("/path/table.pdf", output_format="json")
|
pdfplumber