【Python】操作文档PDF

本文涉及的产品
云解析 DNS,旗舰版 1个月
全局流量管理 GTM,标准版 1个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
简介: 在开发项目过程中,操作PDF的比例在操作文档中,有的使用比例不在少数,多数时候依赖库多到自己没办法选择,现在这里给大家推荐两款比较适合使用的第三方库,使得我们在操作PDF时便利不少,下面开始学习之旅吧。

在开发项目过程中,操作PDF的比例在操作文档中,有的使用比例不在少数,多数时候依赖库多到自己没办法选择,现在这里给大家推荐两款比较适合使用的第三方库,使得我们在操作PDF时便利不少,下面开始学习之旅吧。

🏮1 前言

Python在自动化办公方面有很多实用的第三方库,我们可以从官方网https://pypi.org/search/?q=pd找到很多这种第三方库来供给我们使用,这些库可以很方便的处理wordexcelpptpdf等文件,今天我们就学习一下Python处理PDF文档的两个常用库「pdfplumber」、「pypdf2」。

🎈1.1 pdfplumber

  • 「实验文档」
    官方地址:https://github.com/jsvine/pdfplumber
    PyPi库:https://pypi.org/project/pdfplumber/
  • 「描述」
    探究 PDF 以获取有关每个文本字符、矩形和线条的详细信息。表格提取和可视化在调试阶段。适用于机器产生的pdf文档,而非扫描文档。
  • 「当前版本」
    v0.7.4
  • 「支持版本」
    可以支持python3.7 ~ 3.10 +

🎈1.2 pypdf2

  • 「实验文档」
    PyPi库:https://pypi.org/project/PyPDF2/
  • 「描述」
    PyPDF2 是一个纯 Python PDF 库,免费开源,可以读取文档信息(标题,作者等)、写入、分割、合并PDF文档,它还可以对pdf文档进行添加水印、加密解密等。
  • 「当前版本」
    V2.10.1
  • 「支持版本」
    可以支持python3.6 ~ 3.10 +

🏮2 pdfplumber模块详操

pdfplumber库按页处理 pdf ,获取页面文字,提取表格等操作。

🎈2.1 安装

「安装」

# 网速不好,安装需要一些时间,还有一些依赖库需要安装
Aion.Liu $ pip install pdfplumber
Collecting pdfplumber
  Downloading pdfplumber-0.7.4-py3-none-any.whl(40 kB)     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 40.0/40.0 kB 103.8 kB/s eta 0:00:00Collecting Pillow>=9.1  Using cached Pillow-9.2.0-cp310-cp310-macosx_10_10_x86_64.whl(3.1 MB)Collecting Wand>=0.6.7  Downloading Wand-0.6.10-py2.py3-none-any.whl(142 kB)     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 142.8/142.8 kB 19.0 kB/s eta 0:00:00Collecting pdfminer.six==20220524  Downloading pdfminer.six-20220524-py3-none-any.whl(5.6 MB)     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 5.6/5.6 MB 14.7 kB/s eta 0:00:00Requirement already satisfied: charset-normalizer>=2.0.0in/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages (from pdfminer.six==20220524->pdfplumber)(2.1.0)WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")':/simple/cryptography/Collecting cryptography>=36.0.0  Downloading cryptography-37.0.4-cp36-abi3-macosx_10_10_x86_64.whl(2.8 MB)     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.8/2.8 MB 9.8 kB/s eta 0:00:00WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")':/simple/cffi/Collecting cffi>=1.12  Downloading cffi-1.15.1-cp310-cp310-macosx_10_9_x86_64.whl(179 kB)     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 179.2/179.2 kB 10.1 kB/s eta 0:00:00Collecting pycparser
  Downloading pycparser-2.21-py2.py3-none-any.whl(118 kB)     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 118.7/118.7 kB 9.4 kB/s eta 0:00:00Installing collected packages: Wand, pycparser, Pillow, cffi, cryptography, pdfminer.six, pdfplumber
Successfully installed Pillow-9.2.0 Wand-0.6.10 cffi-1.15.1 cryptography-37.0.4 pdfminer.six-20220524 pdfplumber-0.7.4 pycparser-2.21


最终看到Successfully就知道我又安装了一个python库。

🎈2.2 基本实例

官方提供的实验的基础例子,我没有下载下来文件,提示连接拒绝。这里,我是直接在浏览器访打开这个地址:

https://raw.githubusercontent.com/jsvine/pdfplumber/stable/examples/pdfs/background-checks.pdf


打开就是一个pdf文件,然后右键另存为到你磁盘的某一个目录就可以了。然后在文件所在目录下面执行这个命令,将pdf转为CSV文件:

Aion.Liu $ pdfplumber < background-checks.pdf> background-checks.cs


转换后使用Excel工具打开就看到下面的内容:

关于pdfplumber 转换的一些参数,如下:

参数

描述

--format [format]

csv

json

。json格式返回更多信息;它包括 PDF 级和页面级元数据,以及字典嵌套属性。

--pages [list of pages]

以空格分隔、1索引的页面列表或带连字符的页面范围。例如,1, 11-15,它将返回第 1、11、12、13、14 和 15 页的数据。

--types [list of object types to extract]

选择是char, rect, line, curve, image, annot, 等等。默认为所有可用。

--laparams

一个 JSON 格式的字符串(例如,'{"detect_vertical": true}'

)传递给pdfplumber.open(..., laparams=...)

.

--precision [integer]

四舍五入浮点数的小数位数。默认为无舍入。

🎈2.3 Python库

  • 实验代码
>>> import pdfplumber
>>>>>> with pdfplumber.open('./background-checks.pdf')as pdf:...     first_page = pdf.pages[0]...     print(first_page.chars[0])...
{'matrix':(6.96,0.0,0.0,6.96,47.04,534.7),'fontname':'DCLTEC+Helvetica-Bold','adv':0.667,'upright':True,'x0':47.04,'y0':533.0992,'x1':51.68232,'y1':540.0592,'width':4.642319999999998,'height':6.960000000000036,'size':6.960000000000036,'object_type':'char','page_number':1,'text':'S','stroking_color': None,'non_stroking_color': None,'top':71.94079999999997,'bottom':78.9008,'doctop':71.94079999999997}>>>
  • 解析:pdfplumber.open('文件路径')
    打开一个pdf文件的路径,文件字节码对象或者类文件字节码对象。
  • 解析:pdfplumber.open("文件路径", password = "密码")
    打开一个pdf文件的路径,文件字节码对象或者类文件字节码对象。如果有密码,则需要输入密码,使用password参数。
  • 解析:pdf.pages[0].height
    针对pages这个属性,他是pdfplumber的其中一个属性,他是一个集合,里面有很多参数,例如
  • .page_number :pdf顺序码,默认1,依次类推。
  • .width:宽度
  • .height:高度
  • .objects/ :一个列表,包含一个字典,用于嵌入页面上的每个此类对象。
  • .chars/ :文本字符列表,包含一个字典,用于嵌入页面上的每个此类对象。
  • .lines/ :单一的一维线列表,包含一个字典,用于嵌入页面上的每个此类对象。
  • .rects/ :一个二维矩形列表,包含一个字典,用于嵌入页面上的每个此类对象。
  • .curves/:一个列表,包含一个字典,用于嵌入页面上的每个此类对象。
  • .images:一个图像列表,包含一个字典,用于嵌入页面上的每个此类对象。

其他参数,可以参考下官方提供的文档,这里不在赘述。https://pypi.org/project/pdfplumber/

🎈2.4 提取表格

提取表格的方式是.extract_tables(table_settings={}),其中table_settings是可选项。

  • 实验代码
>>> with pdfplumber.open('./background-checks.pdf')as pdf:...     page = pdf.pages[0]...     page.extract_table()...
[['NICS Firearm Background Checks\nNovember - 2015', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None],['State / Territory','Permit  Handgun Long Gun *Other **Multiple Admin', None, None, None, None, None,'Pre-Pawn\nHandgun Long Gun *Other', None, None,'Redemption\nHandgun Long Gun *Other', None, None,'Returned/Disposition\nHandgun Long Gun *Other', None, None,'Renta# ……此处省略其他。

从上面一段代码,不难看出来,这里是可以提取pdf中的一个表格,并且打印到了控制台。除了提取表格,还可以在提取前设置提取的table_settings属性。

{

   "vertical_strategy" : "lines" ,

   "horizontal_strategy" : "lines" ,

   "explicit_vertical_lines" : [],

   "explicit_horizo ntal_lines" : [],

   "snap_tolerance" : 3 ,

   "snap_x_tolerance" : 3 ,

   "snap_y_tolerance" : 3 ,

   "join_tolerance" : 3 ,

   "join_x_tolerance" : 3 ,

   "join_y_tolerance" : 3 ,

   "edge_min_length": 3 ,

   "min_words_vertical": 3 ,

   "min_words_horizontal" : 1 ,

   "keep_blank_chars" : False,

   "text_tolerance" : 3 ,

   "text_x_tolerance" : 3 ,

   "text_y_tolerance" : 3 ,

   "intersection_tolerance" : 3 ,

   "intersection_x_tolerance" : 3 ,

   "intersection_y_tolerance" : 3 ,

}

属性参数

说明

vertical_strategy

枚举值,可选项包括"lines"

"lines_strict"

"text"

"explicit"

horizontal_strategy

枚举值,可选项包括"lines"

"lines_strict"

"text"

"explicit"

其他参数,可以参考下官方提供的文档,这里不在赘述。https://pypi.org/project/pdfplumber/

🏮3 pypdf2模块详操

虽然PDF文件非常适合以一种便于打印和阅读的方式显示文本,但是对于软件来说,将其解析为纯文本并不容易。因此,PyPDF2在从PDF中提取文本时可能会出错,甚至可能根本无法打开某些PDF。不幸的是,你对此无能为力。PyPDF2可能无法处理某些特定的PDF文件。

🎈3.1 安装

「安装」

Aion.Liu $ python -m pip install pypdf2
Collecting pypdf2
  Downloading PyPDF2-2.10.2-py3-none-any.whl(214 kB)     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 214.3/214.3 kB 317.4 kB/s eta 0:00:00Installing collected packages: pypdf2
Successfully installed pypdf2-2.10.2

pypdf2的安装比起pdfplumber相当简单,PyPDF2 是一个免费的开源纯 python PDF 库。如果您计划使用 PyPDF2 加密或解密使用 AES 的 PDF,您将需要安装一些额外的依赖项。使用常规安装支持使用 RC4 加密。则需要安装下面的依赖:


Aion.Liu $ pip install PyPDF2[crypto]

🎈3.2 基本实例

PyPDF2 可以做更多的事情,例如拆分、合并、读取和创建注释、解密和加密等等。

>>>from PyPDF2 import PdfReader
>>>>>> reader = PdfReader('./background-checks.pdf')>>> number_of_pages = len(reader.pages)>>> page = reader.pages[0]>>>text= page.extract_text()# 页码
>>> print(number_of_pages)1# 分页对象
>>> print(page){'/Type':'/Page','/Parent': IndirectObject(3,0,4326346464),'/Resources': IndirectObject(6,0,4326346464),'/Contents': IndirectObject(4,0,4326346464),'/MediaBox':[0,0,1008,612]}# 内容
>>> print(text)State / TerritoryPermit HandgunLong Gun*Other**MultipleAdminHandgunLong Gun*OtherHandgunLong Gun*OtherHandgunLong Gun*OtherHandgunLong GunHandgunLong Gun*OtherHandgunLong Gun*OtherTotals Alabama18,87023,02222,6508591,1780141502,1792,307110001314032071,137 Alaska2093,0623,2091911840930100100018910000007,095 Arizona2,30312,3829,04170761805301,2736484768196111027,087 Arkansas3,2986,35911,611168376012619222,2751000612100025,048 California98 45241181350074559000004804334000000000180116 Colorado4,14419,78416,0829321,151000000014434000000042,271 Connecticut9,63111,5945,0721340700000000000000026,438 Delaware2042,1522,4246572034017120000592404005,040 District of Columbia854200000000000000000064 Florida 15,90750,79628,9812,2681,9571218902,2481,1352405036190000103,532Georgia 14,11116,63515,2274487580101401,7721,7964000109100050,795Guam 0100551230000100000000000171Hawaii 1,248000000000001300000001,252Idaho 1,9443,6095,22719018900402734551224112003011,925Illinois 87,19024,41217,22701,0320000000000000000129,861Indiana 81,93525,51920,2271,1138080230136295280031131240130,333Iowa 8,7852674,59627437010071042000000013,794Kansas 8947,0868,70231139631314865302200610000018,433Kentucky 264,14012,15514,847254648191101,4912,3152220680000295,891Louisiana 1,94514,70817,368697793051128841,3233000110101037,752Maine 2994,0484,38713517120007016506704300009,297Mariana Islands 0000000000000000000000Maryland 1,5123,2208,3109690030722132143116100013,463Massachusetts 5,2146,0833,93140217500102501014223500015,885Michigan 16,78613,63417,6043852381,025140548926924041123150,278Minnesota 18,9399,37314,17348633001201765120811026002244,023Mississippi 6189,78513,1912675239282001,1711,874100066320027,504Missouri 5,88421,13522,8521,0041,0600111601,1311,7543991143325603055,031Montana 8522,8485,17090197101463918281114002000010,415Nebraska 4,2581733,7242310010059617000010008,299Nevada 1,5434,8893,2721932870000284163010000000010,632New Hampshire 3,6304,8474,165952100002316911122001012,850New Jersey 03,4624,704147000000000000000008,313New Mexico 8295,2474,97433427702313976181330004010012,721New York 2,9068,65023,5196651490030162500002432201654036,421North Carolina 22,4691,37020,1075762020162501,7712,6447000226110049,217North Dakota 4531,7203,744657900306515700001100006,288Ohio 9,33834,87831,8171,3921,4830241611,2281,38940002122110181,616Oklahoma 015,00514,753778998011711,6392,22660001121001035,457Oregon 3513,58611,83200000000000000000025,453Pennsylvania 24,13662,75216,29700580000004461470000000103,836Puerto Rico 01,033170112000006100000000101,242Rhode Island 095493257135000034000012211002,101South Carolina 7,28411,45210,39356143803809799123164046010032,064South Dakota 8192,7655,484143151001012323900001100009,727Tennessee 9,50928,81524,02301,3000000000171500000063,670Texas 21,55056,94151,6702,5323,0480292005,7485,3312112142364150146,982Utah 10,4294,3145,85719526200102092851140582100000021,772Vermont 01,1891,826497000100100000000003,136Virgin Islands 93132010000000000000000109Virginia 62224,05222,34897400000000104000000048,010Washington 10,31415,82212,4251,23860648801,0961,129335615934443401969043,989West Virginia 2,2176,95311,56122447824909232,678300038000025,063Wisconsin 5,86713,70017,7594584500301245133152041015103138,541Wyoming 3831,7452,37287104104013218400001200205,017Totals 804,006671,330636,90326,59723,0151,2812182491329,90538,4871021,65653344001,06790565314552,236,457NICS Firearm Background ChecksNovember -2015Pre-PawnRedemptionReturned/DispositionRentalsPrivate SaleReturn to Seller - Private Sale
NOTES:*Refers to frames, receivers and other firearms that are not either handguns orlong guns (rifles or shotguns), such as firearms having a pistol grip that expel a shotgun shell**Multiple (multiple types of firearms selected)DISCLAIMERS:Some states may reflect lower than expected numbers for handgun checks based on varying state laws pertaining to handgun permits  Since the permit check is done in place of the NICS check in most of the affected states, the low handgun statistics are often balanced out by a higher number of handgun permit checksThese statistics represent the number of firearm background checks initiated through the NICS   They do not represent the number of firearms sold   Based on varying state laws and purchase scenarios, a one-to-one correlation cannot be made between a firearm background check and a firearm salePage 1 of 205>>>


总结

本文按照官方提供的示例实验操作,给自己学习增添不少便利。

相关文章
|
9天前
|
C++ Python
《从零开始学Python》(第二版) PDF下载读书分享
Python,由Guido van Rossum创造(1989),是1991年发布的面向对象、解释型编程语言,以其简洁清晰的语法和强大的库著称,昵称“胶水语言”。它连接不同模块,强调代码的优雅、明确和简单。《从零开始学Python》(第二版)是本风趣、实践导向的教材,提供PDF下载,是学习Python的宝贵资源。![书封](https://ucc.alicdn.com/pic/developer-ecology/nrw3f3oqlpmag_40f357729aac4defa97fb1e0f66a2501.png)
18 1
《从零开始学Python》(第二版) PDF下载读书分享
|
2天前
|
自然语言处理 程序员 编译器
`pylatex`是一个Python库,用于生成LaTeX文档。LaTeX是一种用于高质量排版和打印的文档准备系统,特别适用于科学、技术和数学文档。
`pylatex`是一个Python库,用于生成LaTeX文档。LaTeX是一种用于高质量排版和打印的文档准备系统,特别适用于科学、技术和数学文档。
11 2
|
3天前
|
Python
|
7天前
|
数据处理 开发者 Python
【Python】已解决:FileNotFoundError: [Errno 2] No such file or directory: ‘E:\自动备份文档\Python\修改配置.csv‘
【Python】已解决:FileNotFoundError: [Errno 2] No such file or directory: ‘E:\自动备份文档\Python\修改配置.csv‘
15 1
|
7天前
|
SQL 关系型数据库 MySQL
「Python入门」python操作MySQL和SqlServer
**摘要:** 了解如何使用Python的pymysql模块与MySQL数据库交互。首先,通过`pip install pymysql`安装模块。pymysql提供与MySQL的连接功能,例如创建数据库连接、执行SQL查询。在设置好MySQL环境后,使用`pymysql.connect()`建立连接,并通过游标执行SQL(如用户登录验证)。注意防止SQL注入,使用参数化查询。增删改操作需调用`conn.commit()`来保存更改。pymssql模块类似,但导入和连接对象创建略有不同。
11 0
「Python入门」python操作MySQL和SqlServer
|
7天前
|
数据挖掘 Python
利用Python进行数据分析PDF下载经典数据分享推荐
**Python数据分析大师作,Wes McKinney亲著,详述数据操作、清洗与分析。第2版面向Python 3.6,涵盖pandas、NumPy、IPython和Jupyter更新,实战案例丰富;第3版已升级至Python 3.10和pandas 1.4,继续引领数据科学潮流。[PDF下载](https://zhangfeidezhu.com/?p=337)**
15 0
利用Python进行数据分析PDF下载经典数据分享推荐
|
11天前
|
JavaScript 数据库
文本,在线浏览PDF,一个最简单的文档标准样式,文档预览非常简单的样式,文档管理样式设计,标准,好的设计
文本,在线浏览PDF,一个最简单的文档标准样式,文档预览非常简单的样式,文档管理样式设计,标准,好的设计
|
2天前
|
Unix Linux Shell
Sphinx是一个Python文档生成工具,它可以解析reStructuredText或Markdown格式的源代码注释,并生成多种输出格式,如HTML、LaTeX、PDF、ePub等。
Sphinx是一个Python文档生成工具,它可以解析reStructuredText或Markdown格式的源代码注释,并生成多种输出格式,如HTML、LaTeX、PDF、ePub等。
5 0
|
6天前
|
UED Python
【Python】已解决:FileNotFoundError: [Errno 2] No such file or directory: ‘D:\1. PDF’
【Python】已解决:FileNotFoundError: [Errno 2] No such file or directory: ‘D:\1. PDF’
12 0
|
12天前
|
API Python
Python学习日记(二:函数和逻辑操作)
Python中的函数和逻辑操作至关重要。函数包括可变和不可变参数。