pdfplumber处理pdf文件

发布时间 2023-03-23 15:00:45作者: niko5960

pdfplumber官方文档

https://github.com/hbh112233abc/pdfplumber


文档上对open方法的介绍

Loading a PDF
To start working with a PDF, call pdfplumber.open(x), where x can be a:

  • path to your PDF file
  • file object, loaded as bytes
  • file-like object, loaded as bytes

从本地读取pdf文件

with pdfplumber.open("path/to/file.pdf") as pdf:

从网络流获取file like object类的方法

python提供了两个产生file like object的方法

  1. stringio
from io import StringIO
f = StringIO()
f.write('hello')
#或者
f = StringIO('Hello World')
  1. bytesio
from io import BytesIO

# 向内存中写入二进制数据
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue()) 

#或者
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
# 读取、并打印二进制数据
print(f.read()) 

open方法加载文件后返回一个 pdfplumber.PDF 实例.
对于有密码的pdf文件可以使用password参数

pdfplumber.open("file.pdf", password = "test")

pdfplumber.PDF类


pdfplumber.PDF 类代表一个PDF文件,主要有以下两个属性:

  1. metadata
    元数据,摘自pdf创建信息
  2. pages
    包含pdfplumber.Page(页实例)的列表。

pdfplumber.Page 类


pdfplumber.Page大部分操作都围绕此进行

主要属性

.page_number:页码
.width:页面宽度
.height:页面高度
.objects / .chars / .lines / .rects / .curves / .images:这些属性中的每一个都是一个列表,每个列表都为嵌入在页面上的每个此类对象包含一个字典。

提取文本

.extract_text

提取表格

.extract_tables(table_settings={}):从当前页面所有表格中提取表格,返回从页面上找到的所有表中提取的文本,表示为列表列表列表,其结构为“表->行->单元格”
.extract_table(table_settings={}):返回从页面上最大表中提取的文本,该表表示为列表列表,其结构为“行->单元格”。如果一样多那就提取最靠近页面顶部的表格

示例

pdf = pdfplumber.open("path/to/my.pdf")
page = pdf.pages[0]
page.extract_table()