python通過第三方庫操作PDF文件的幾種常見方法
前言
大家好,有關(guān)python操作pdf的方法,各種語言處理起來都比較麻煩,而且各種第三方庫的應(yīng)用場景都不同。下面說明一下python如何通過第三方庫如何處理pdf文件。
一、文本內(nèi)容提取
1.1、pdfplumber提取文本內(nèi)容
安裝pdfplumber
# 安裝模塊 pip install pdfplumber
pdfplumber提取PDF中文字代碼思路如下
- 利用pdfplumber打開一個(gè) PDF 文件
- 獲取指定的頁,或者遍歷每一頁
- 利用.extract_text()方法提取當(dāng)前頁的文字
import pdfplumber import os path = os.getcwd() filepath = os.path.join(path,"原則.pdf") with pdfplumber.open(filepath) as pdf: for i in range(len(pdf.pages)): page = pdf.pages[i] print(page.extract_text())
1.2、pdfminer提取文本內(nèi)容
安裝pdfminer,注意安裝順序
pip install pdfminer3k pip install pdfminer.six
pdfminer.six提取PDF中文字代碼思路如下
- 利用open打開一個(gè) PDF 文件
- 通過pdfdocument文檔管理器讀取pdf文件
- 通過PDFPageInterpreter解析器文檔讀取
- 通過PDFPageAggregator聚合器獲取頁面內(nèi)容
- 利用.get_text()方法提取當(dāng)前頁的文字
讀取pdf內(nèi)容
from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument fp = open("原則.pdf","rb") pdfparser = PDFParser(fp) doc = PDFDocument(pdfparser)
構(gòu)造解析器和聚合器,下面這么邏輯步驟固定格式,直接這么寫就可以。
from pdfminer.pdfinterp import PDFResourceManager from pdfminer.pdfinterp import PDFPageInterpreter from pdfminer.converter import PDFPageAggregator from pdfminer.layout import LAParams #pdf資源管理器 resource = PDFResourceManager() #參數(shù)分析器 laparam = LAParams() #頁面聚合器 device = PDFPageAggregator(resource,laparams=laparam) #頁面解釋器 interpreter = PDFPageInterpreter(resource,device)
輸出pdf內(nèi)容
from pdfminer.pdfpage import PDFPage for page in PDFPage.create_pages(doc): #使用頁面解釋器讀取 interpreter.process_page(page) #使用聚合器來獲取內(nèi)容 layout = device.get_result() for out in layout: #需要注意的是pdf文件不僅文字,還有圖片等內(nèi)容, # 為了避免錯(cuò)誤,我們判斷是否為文本 if(hasattr(out,'get_text')): print(out.get_text())
二、表格內(nèi)容提取
表格內(nèi)容我們也使用pdfplumber
。安裝過程和操作步驟也相同,提取表格,我們使用extract_table()
方法提取表格內(nèi)容,使用pandas.DataFrame
顯示內(nèi)容。
import os import pandas as pd import pdfplumber path = os.getcwd() pdf = pdfplumber.open(os.path.join(path,"table.pdf")) p0 = pdf.pages[0] table = p0.extract_table() df = pd.DataFrame(table[1:],columns=table[0]) print(df)
三、內(nèi)容拆分
拆分和合并我們一般使用PyPDF2庫
from PyPDF2 import PdfWriter,PdfReader
這里導(dǎo)入了兩個(gè)方法:
- PdfReader 可以理解為讀取器
- PdfWriter 可以理解為寫入器
def split_pdf(infn,outfn,start,end): ''' :param infn 源pdf路徑 :param outfn 目的pdf路徑 :param start 開始頁面 :param end 結(jié)束頁面 return ''' pdf_output = PdfWriter() pdf_input = PdfReader(open(infn,"rb")) page_count = len(pdf_input.pages) if end > page_count: end = page_counte #分割pdf頁面,輸出新的內(nèi)容 for i in range(start,end): pdf_output.add_page(pdf_input.pages[i]) pdf_output.write(open(outfn,'wb')) split_pdf("原則.pdf","原則2.pdf",5,10)
四、內(nèi)容合并
這里導(dǎo)入了兩個(gè)方法:
- PdfReader 可以理解為讀取器
- PdfMerger可以理解為合并器
from PyPDF2 import PdfMerger,PdfReader def merge_pdf(filenames,merge_name,password=None): ''' :param filenames 傳遞一個(gè)文件列表 :param merge_name 合并后的文件 :param password 對應(yīng)的密碼列表 return ''' files = len(filenames) pdf_merge = PdfMerger(False) for i in range(files): pdf_reader = PdfReader(open(filenames[i],"rb")) if(not pdf_reader): return pdf_merge.append(pdf_reader) pdf_merge.write(open(merge_name,"wb")) merge_pdf(['原則1.pdf','原則2.pdf'],'原則3.pdf')
五、通過命令工具生成pdf文檔
可以借助命令行工具進(jìn)行pdf文檔的生成。wkhtmltopdf命令行和第三庫pdfkit。
去網(wǎng)上下載wkhtmltopdf工具
# 安裝pdfkit庫 pip install pdfkit
5.1 網(wǎng)頁內(nèi)容生成pdf
import pdfkit def url_to_pdf(url, to_file): # 將wkhtmltopdf.exe程序絕對路徑傳入config對象 path_wkthmltopdf = r'D:\\tool\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) # 生成pdf文件,to_file為文件路徑 pdfkit.from_url(url, to_file, configuration=config) print('完成') url_to_pdf('https://www.baidu.com','D:\baidu.pdf')
5.2 本地網(wǎng)頁內(nèi)容生成pdf
#避免亂碼在html文件中,<meta charset="UTF-8"> def html_to_pdf(html, to_file): # 將wkhtmltopdf.exe程序絕對路徑傳入config對象 path_wkthmltopdf = r'D:\\tool\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) # 生成pdf文件,to_file為文件路徑 pdfkit.from_file(html, to_file, configuration=config) html_to_pdf('sample.html','out_2.pdf')
5.3 字符串內(nèi)容生成pdf
'''將字符串生成pdf文件''' def str_to_pdf(string, to_file): # 將wkhtmltopdf.exe程序絕對路徑傳入config對象 path_wkthmltopdf = r'D:\\tool\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) # 生成pdf文件,to_file為文件路徑 pdfkit.from_string(string, to_file, configuration=config) print('完成') str_to_pdf('This is test!','out_3.pdf')
總結(jié)
到此這篇關(guān)于python通過第三方庫操作PDF文件的幾種常見方法的文章就介紹到這了,更多相關(guān)python操作PDF文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于PyTorch實(shí)現(xiàn)一個(gè)簡單的CNN圖像分類器
本文記錄了一個(gè)簡單的基于pytorch的圖像多分類器模型構(gòu)造過程,參考自Pytorch官方文檔、磐創(chuàng)團(tuán)隊(duì)的《PyTorch官方教程中文版》以及余霆嵩的《PyTorch 模型訓(xùn)練實(shí)用教程》。從加載數(shù)據(jù)集開始,包括了模型設(shè)計(jì)、訓(xùn)練、測試等過程。2021-05-05Python調(diào)用GPU算力的實(shí)現(xiàn)步驟
本文介紹了在Python中調(diào)用GPU算力的基本步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-03-03python實(shí)現(xiàn)將JPG、BMP圖片轉(zhuǎn)化為bgr
這篇文章主要介紹了python實(shí)現(xiàn)將JPG、BMP圖片轉(zhuǎn)化為bgr方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03pandas DataFrame.shift()函數(shù)的具體使用
本文主要介紹了pandas DataFrame.shift()函數(shù)的使用,pandas DataFrame.shift()函數(shù)可以把數(shù)據(jù)移動指定的位數(shù),有需要了解pandas DataFrame.shift()用法的朋友可以參考一下2021-05-05Python處理Excel的14個(gè)常用操作總結(jié)
在數(shù)據(jù)處理和分析的領(lǐng)域中,Excel是一種被廣泛使用的工具,然而,通過Python處理Excel,能夠更好地實(shí)現(xiàn)自動化和批量處理,本文為大家整理了14個(gè)Python處理Excel的常用操作,希望對大家有所幫助2023-12-12Python?識別錄音并轉(zhuǎn)為文字的實(shí)現(xiàn)
本文主要介紹了Python?識別錄音并轉(zhuǎn)為文字的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03