目录1.Python操作pdf(pdfplumber读取PDF写入Exce)1.1安装pdfplumber模块库1.2常用操作1.2.1Python读取pdf文件案例1.2.2Python...
目录
1. python 操作pdf(pdfplumber读取PDF写入Exce)1.1 安装pdfplumber模块库
1.2 常用操作
1.2.1 Python读取pdf文件案例
1.2.2 Python读取pdf文件代码
1.2.3 Python读取pdf文件存入Excel代码
1. Python 操作pdf(pdfplumber读取PDF写入Exce)
1.1 安装pdfplumber模块库
安装pdfplumber:
pip install pdfplumber
pdfplumber.PDF类
pdfplumber.PDF类表示单个PDF ,并具有两个主要属性:
pdfplumber.Page类
pdfplumber.Page类常用属性
常用方法:
但是在解析js大型PDF时,这些缓存的属性可能需要大量内存。您可以使用此方法刷新缓存并释放内存。
1.2 常用操作
PDF是Portable Document Format的缩写,这类文件通常使用.pdf作为其扩展名。在日常开发工作中,最容易遇到的就是从PDF中读取文本内容以及用已有的内容生成PDF文档这两个任务。
2.输出总页数
3.读取第一页宽度、高度等信息
4.读取文本第一页
加载pdf:
pdfplumber.open( "路径/文件名. pdf".pas sword="test "laparams={ "line_ _overlap'”0.7 })password : 要加载受密码保护的PDF ,请传递password关键字参数
laparams :要将布局分析参数设置为pdfminer. six的布局引擎,请传递laparams关键字参数
1.2.1 Python读取pdf文件案例
pdf文件如下:

1.2.2 Python读取pdf文件代码
import pdfplumber
# 加载pdf
path = "C:/Users/Administrator/Desktop/test08/test11 - 多页.pdf"
with pdfplumber.open(path) as pdf:
print(pdf)
print(type(pdf))
# 读取pdf文档信息
print("pdf文档信息:", pdf.metadata)
# 输出总页数
print("pdf文档总页数:", len(pdf.pages))
# 1.读取第一页宽度、高度等信息
first_page = pdf.pages[0] # pdfplumber.Page对象第一页
# 查看页码
print('pdf页码:', first_page.page_number)
# 查看页宽
print('pdf页宽:', first_page.width)
# 查看页高
print('pdf页高:', first_page.height)
# 2.读取文本第一页
first_page = pdf.pages[0] # pdfplumber.Page对象第一页
text = first_page.extract_text()
print(text)
执行结果:
"D:\Program Files1\Python\python.exe" D:/Pycharm-work/pythonTest/打卡/0811读www.cppcns.com取pdf.py
<pdfplumber.pdf.PDF object at 0x0000000002846278>
<class 'pdfplumber.pdf.PDF'>
pdf文档信息: {'Author': '', 'Comments': '', 'Company': '', 'CreationDate': "D:20220812102327+02'23'", 'Creator': 'wpS 表格', 'Keywords': '', 'ModDate': "D:20220812102327+02'23'", 'Producer': '', 'SourceModified': "D:20220812102327+02'23'", 'Subject': '', 'Title': '', 'Trapped': 'False'}
pdf文档总页数: 2
pdf页码: 1
pdf页宽: 595.25
pdf页高: 841.85
姓名 年龄 性别 地址 学习技能
张三 20 女 北京 python
李四 25 男 深圳 Java
赵五 28 男 上海 C++
孙六 23 女 广州 python
钱七 27 男 珠海 python
张101 20 女 北京 python
.......
.......
张150 27 男 珠海 python
张151 20 女 北京 python
张152 25 男 深圳 javaProcess finished with exit code 0
1.2.3 Python读取pdf文件存入Excel代码
import pdfplumber
import xlwt
# 加载pdf
path = "C:/Users/Administrator/Desktop/test08/test11 - 多页.pdf"
with pdfplumber.open(path) as pdf:
page_1 = pdf.pages[0] # pdf第一页
table_1 = page_1.extract_table() # 读取表格数据
print(table_1)
# 1.创建Excel对象
workbook = xlwt.Workbook(encoding='utf8')
# 2.新建sheet表
worksheet = workbook.add_sheet('Sheet1')
# 3.自定义列名
clo1 = table_1[0]
# 4.将列表元组clo1写入sheet表单中的第一行
for i in range(0, len(clo1)):
worksheet.write(0, i, clo1[i])
# 5.将数据写进sheet表单中
for i in range(0, len(table_1[1:])):
data = table_1[1:][i]
for j in range(0, len(clo1)):
worksheet.write(i + 1, j, data[j])
# 保存Excel文件分两种
workbook.save('test88.xls')
执行结果:

到此这篇关于Python 操作pdf pdfplumber读取PDF写入Exce的文章就介绍到这了,更多相关Python 操作pdf内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!










