天天看點

【Python】操作文檔PDF

在開發項目過程中,操作PDF的比例在操作文檔中,有的使用比例不在少數,多數時候依賴庫多到自己沒辦法選擇,現在這裡給大家推薦兩款比較适合使用的第三方庫,使得我們在操作PDF時便利不少,下面開始學習之旅吧。

🏮1 前言

Python在自動化辦公方面有很多實用的第三方庫,我們可以從官方網​​https://pypi.org/search/?q=pd​​找到很多這種第三方庫來供給我們使用,這些庫可以很友善的處理​

​word​

​、​

​excel​

​、​

​ppt​

​、​

​pdf​

​等檔案,今天我們就學習一下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:00
Collecting 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:00
Collecting 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:00
Requirement already satisfied: charset-normalizer>=2.0.0 in /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:00
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/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:00
Collecting pycparser
  Downloading pycparser-2.21-py2.py3-none-any.whl (118 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 118.7/118.7 kB 9.4 kB/s eta 0:00:00
Installing 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工具打開就看到下面的内容:

【Python】操作文檔PDF

關于​

​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:00
Installing 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 基本執行個體

>>> 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 45241 18135 00745 5 9000004804334000000000180 116 Colorado4,14419,78416,0829321,151000000014434000000042,271 Connecticut9,63111,5945,0721340700000000000000026,438 Delaware2042,1522,4246572034017120000592404005,040 District of Columbia854200000000000000000064 Florida 15,907 50,796 28,981 2,268 1,957 121 8 9 02 , 2 4 81 , 1 3 5 2 40 5 0 36 19 0 0 0 01 0 3 , 5 3 2
Georgia 14,111 16,635 15,227 448 758 0 10 14 01 , 7 7 21 , 7 9 6 4 0 0 0 10 9 1 0 0 05 0 , 7 9 5
Guam 0 100 55 12 30 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 171
Hawaii 1,248 00 0 0 0 0 0 0 0 0 0 1 3 0 0 0 0 0 0 01 , 2 5 2
Idaho 1,944 3,609 5,227 190 189 0 0 4 0 273 455 1 22 4 1 1 2 0 0 3 01 1 , 9 2 5
Illinois 87,190 24,412 17,227 0 1,032 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 01 2 9 , 8 6 1
Indiana 81,935 25,519 20,227 1,113 808 0 2 3 0 13 629 5 28 0 0 31 13 1 2 4 01 3 0 , 3 3 3
Iowa 8,785 267 4,596 27 4 37 0 1 0 0 71 0 4 2 0 0 0 0 0 0 01 3 , 7 9 4
Kansas 894 7,086 8,702 311 396 3 1 3 1 486 530 2 2 0 0 6 10 0 0 0 01 8 , 4 3 3
Kentucky 264,140 12,155 14,847 254 648 1 9 11 01 , 4 9 12 , 3 1 5 2 2 2 0 6 8 0 0 0 02 9 5 , 8 9 1
Louisiana 1,945 14,708 17,368 697 793 0 5 11 2 884 1,323 3 0 0 0 1 10 1 0 1 03 7 , 7 5 2
Maine 299 4,048 4,387 135 171 2 0 0 0 70 165 0 6 7 0 4 3 0 0 0 09 , 2 9 7
Mariana Islands 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Maryland 1,512 3,220 8,310 96 90 0 3 0 72 213 2 14 3 1 1 6 1 0 0 01 3 , 4 6 3
Massachusetts 5,214 6,083 3,931 402 175 0 0 1 0 2 5 0 1 0 1 42 23 5 0 0 01 5 , 8 8 5
Michigan 16,786 13,634 17,604 385 238 1,025 1 4 0 5 489 2 69 24 0 4 1 1 2 3 15 0 , 2 7 8
Minnesota 18,939 9,373 14,173 486 330 0 1 2 0 176 512 0 8 11 0 2 6 0 0 2 24 4 , 0 2 3
Mississippi 618 9,785 13,191 267 523 9 28 20 01 , 1 7 11 , 8 7 4 1 0 0 0 6 6 3 2 0 02 7 , 5 0 4
Missouri 5,884 21,135 22,852 1,004 1,060 0 11 16 01 , 1 3 11 , 7 5 4 3 99 11 4 33 25 6 0 3 05 5 , 0 3 1
Montana 852 2,848 5,170 90 197 10 1 4 6 391 828 1 11 4 0 0 2 0 0 0 01 0 , 4 1 5
Nebraska 4,258 173 3,724 23 10 0 1 0 0 5 96 1 7 0 0 0 0 1 0 0 08 , 2 9 9
Nevada 1,543 4,889 3,272 193 287 0 0 0 0 284 163 0 1 0 0 0 0 0 0 0 01 0 , 6 3 2
New Hampshire 3,630 4,847 4,165 95 21 0 0 0 0 23 1 69 11 1 2 2 0 0 1 01 2 , 8 5 0
New Jersey 03 , 4 6 2 4 , 7 0 4 147 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 08 , 3 1 3
New Mexico 829 5,247 4,974 334 277 0 2 3 1 397 618 1 33 0 0 0 4 0 1 0 01 2 , 7 2 1
New York 2,906 8,650 23,519 665 149 0 0 3 0 16 25 0 0 0 0 243 220 16 5 4 03 6 , 4 2 1
North Carolina 22,469 1,370 20,107 576 202 0 16 25 01 , 7 7 12 , 6 4 4 7 0 0 0 2 26 1 1 0 04 9 , 2 1 7
North Dakota 453 1,720 3,744 65 79 0 0 3 0 65 157 0 0 0 0 1 1 0 0 0 06 , 2 8 8
Ohio 9,338 34,878 31,817 1,392 1,483 0 24 16 11 , 2 2 81 , 3 8 9 4 0 0 0 21 22 1 1 0 18 1 , 6 1 6
Oklahoma 01 5 , 0 0 5 1 4 , 7 5 3 778 998 0 11 7 11 , 6 3 92 , 2 2 6 6 0 0 0 11 21 0 0 1 03 5 , 4 5 7
Oregon 35 13,586 11,832 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 02 5 , 4 5 3
Pennsylvania 24,136 62,752 16,297 0 0 58 0 0 0 0 0 0 446 147 0 0 0 0 0 0 01 0 3 , 8 3 6
Puerto Rico 01 , 0 3 3 170 11 20 0 0 0 0 6 1 0 0 0 0 0 0 0 0 1 01 , 2 4 2
Rhode Island 0 954 932 57 135 0 0 0 0 3 4 0 0 0 0 12 2 1 1 0 02 , 1 0 1
South Carolina 7,284 11,452 10,393 561 438 0 3 8 0 979 912 3 16 4 0 4 6 0 1 0 03 2 , 0 6 4
South Dakota 819 2,765 5,484 143 151 0 0 1 0 123 239 0 0 0 0 1 1 0 0 0 09 , 7 2 7
Tennessee 9,509 28,815 24,023 0 1,300 0 0 0 0 0 0 0 17 1 5 0 0 0 0 0 06 3 , 6 7 0
Texas 21,550 56,941 51,670 2,532 3,048 0 29 20 05 , 7 4 85 , 3 3 1 21 1 2 1 42 36 4 1 5 01 4 6 , 9 8 2
Utah 10,429 4,314 5,857 195 262 0 0 1 0 209 285 1 140 58 21 0 0 0 0 0 02 1 , 7 7 2
Vermont 01 , 1 8 9 1 , 8 2 6 49 70 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 03 , 1 3 6
Virgin Islands 93 13 20 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 109
Virginia 622 24,052 22,348 974 00 0 0 0 0 0 0 10 4 0 0 0 0 0 0 04 8 , 0 1 0
Washington 10,314 15,822 12,425 1,238 606 4 8 8 01 , 0 9 61 , 1 2 9 3 356 159 3 444 340 19 6 9 04 3 , 9 8 9
West Virginia 2,217 6,953 11,561 224 478 2 4 9 0 923 2,678 3 0 0 0 3 8 0 0 0 02 5 , 0 6 3
Wisconsin 5,867 13,700 17,759 458 45 0 0 3 0 124 513 3 15 20 4 10 15 1 0 3 13 8 , 5 4 1
Wyoming 383 1,745 2,372 87 104 1 0 4 0 132 184 0 0 0 0 1 2 0 0 2 05 , 0 1 7
Totals 804,006 671,330 636,903 26,597 23,015 1,281 218 249 13 29,905 38,487 102 1,656 533 44 0 01 , 0 6 7 905 65 31 45 52 , 2 3 6 , 4 5 7NICS Firearm Background ChecksNovember - 2015Pre-PawnRedemptionReturned/DispositionRentalsPrivate SaleReturn to Seller - Private Sale
NOTES:*Refers to frames, receivers and other firearms that are not either handguns or long 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
>>>      

總結