python讀取pdf檔案,有的時候在開發過程中會用到,讀取pdf檔案的內容來做一些應用。
方法/步驟
首先要下載一個處理pdf的元件pdfminer,百度搜索去官網下載
下載完成解壓以後,開啟cmd進入用命令安裝。python setup.py install 進行安裝
我們來測試一下是否安裝成功了,引入這個模組,執行一下程式碼,沒有報錯就說明安裝成功了
官網有文件也有程式碼示例
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice
fp = open('mypdf.pdf', 'rb')
#建立一個PDF文件解析器物件
parser = PDFParser(fp)
#建立一個PDF文件物件儲存文件結構
#提供密碼初始化,沒有就不用傳該引數
document = PDFDocument(parser, password)
#檢查檔案是否允許文字提取
if not document.is_extractable:
raise PDFTextExtractionNotAllowed
#建立一個PDF資源管理器物件來儲存共享資源
rsrcmgr = PDFResourceManager()
#建立一個pdf裝置物件
device = PDFDevice(rsrcmgr)
#建立一個PDF解析器物件
interpreter = PDFPageInterpreter(rsrcmgr, device)
#處理文件當中的每個頁面
for page in PDFPage.create_pages(document):
interpreter.process_page(page)
我新建一個pdf,新輸入一些內容
執行一下程式碼,看一下效果