基于Python實現(xiàn)PDF轉(zhuǎn)換文件格式
最近工作中經(jīng)常遇到收到其他人提供的pdf文檔,想要編輯修改下或者復(fù)制部分內(nèi)容比較困難,想通過現(xiàn)有的pdf工具軟件轉(zhuǎn)換文檔格式,基本都要充錢,為了免費實現(xiàn)pdf轉(zhuǎn)換工具,網(wǎng)上查了下相關(guān)技術(shù)方案,整理了下代碼,測試真實有效,分享下。
第一步,安裝相關(guān)第三方庫
pip install PyMuPDF -i https://mirrors.aliyun.com/pypi/simple pip install pdf2docx -i https://mirrors.aliyun.com/pypi/simple
第二步,編寫代碼
pdfConverter.py:
import datetime
import os
# fitz就是pip install PyMuPDF
import fitz
# pdf2docx 也是封裝 fitz 模塊為基礎(chǔ)開發(fā)的
from pdf2docx import Converter
'''
pdf 轉(zhuǎn)換工具包
pdf 轉(zhuǎn)成 word
pdf 轉(zhuǎn)成 圖片
pdf 轉(zhuǎn)成 html
'''
def pdf2word(file_path):
'''
@方法名稱: pdf轉(zhuǎn)word
@中文注釋: pdf轉(zhuǎn)word
@入?yún)?
@param file_path str pdf文件路徑
@出參:
@返回狀態(tài):
@return 0 失敗或異常
@return 1 成功
@返回錯誤碼
@返回錯誤信息
@param doc_file str word文件名
@作 者: PandaCode輝
@創(chuàng)建時間: 2023-10-16
@使用范例: pdf2word('test.pdf')
'''
try:
if (not type(file_path) is str):
return [0, "111111", "pdf文件路徑參數(shù)類型錯誤,不為字符串", [None]]
# 開始時間
startTime = datetime.datetime.now()
# 提取文件名,去除文件后綴
file_name = file_path.split('.')[0]
print(file_name)
# word文件名
doc_file = f'{file_name}.docx'
print(doc_file)
p2w = Converter(file_path)
'''
convert(doc_file,start,end)函數(shù)中
doc_file:轉(zhuǎn)化完成后文件名
start:轉(zhuǎn)化開始頁面
end:轉(zhuǎn)化結(jié)束頁面
注意點:
①若不給start,end參數(shù)則默認(rèn)轉(zhuǎn)化全篇
②對于不連續(xù)的頁面,也可寫作convert(doc_file , pages = [2,4,6])
'''
p2w.convert(doc_file, start=0, end=None)
p2w.close()
endTime = datetime.datetime.now() # 結(jié)束時間
print('pdf轉(zhuǎn)word耗時: %s 秒' % (endTime - startTime).seconds)
print("pdf轉(zhuǎn)word成功")
# 返回容器
return [1, '000000', 'pdf轉(zhuǎn)word成功', [doc_file]]
except Exception as e:
p2w.close()
print("pdf轉(zhuǎn)word異常," + str(e))
return [0, '999999', "pdf轉(zhuǎn)word異常," + str(e), [None]]
def pdf2image(file_path, image_path):
'''
@方法名稱: pdf轉(zhuǎn)圖片
@中文注釋: pdf轉(zhuǎn)圖片
@入?yún)?
@param file_path str pdf文件路徑
@param image_path str 輸出圖片路徑
@出參:
@返回狀態(tài):
@return 0 失敗或異常
@return 1 成功
@返回錯誤碼
@返回錯誤信息
@param image_path str 輸出圖片路徑
@作 者: PandaCode輝
@創(chuàng)建時間: 2023-10-16
@使用范例: pdf2image('test.pdf', './images')
'''
try:
if (not type(file_path) is str):
return [0, "111111", "pdf文件路徑參數(shù)類型錯誤,不為字符串", [None]]
if (not type(image_path) is str):
return [0, "111112", "輸出圖片路徑參數(shù)類型錯誤,不為字符串", [None]]
# 開始時間
startTime = datetime.datetime.now()
print("pdfPath=" + file_path)
# 提取文件名,去除文件后綴
file_name = file_path.split('.')[0]
print(file_name)
print("imagePath=" + imagePath)
# 打開pdf文檔
pdfDoc = fitz.open(file_path)
# 判斷存放圖片的文件夾是否存在
if not os.path.exists(image_path):
# 若圖片文件夾不存在就創(chuàng)建
os.makedirs(image_path)
# Document.page_count 頁數(shù) (int)
# 循環(huán)頁數(shù)
for pg in range(pdfDoc.page_count):
print('=======%s========' % (pg + 1))
'''
頁面(Page)處理是MuPDF功能的核心。
您可以將頁面呈現(xiàn)為光柵或矢量(SVG)圖像,可以選擇縮放、旋轉(zhuǎn)、移動或剪切頁面。
您可以提取多種格式的頁面文本和圖像,并搜索文本字符串。
對于PDF文檔,可以使用更多的方法向頁面添加文本或圖像。
'''
page = pdfDoc[pg]
rotate = int(0)
# 每個尺寸的縮放系數(shù)為1.3,這將為我們生成分辨率提高2.6的圖像。
# 此處若是不做設(shè)置,默認(rèn)圖片大小為:792X612, dpi=96
zoom_x = 1.33333333 # (1.33333333-->1056x816) (2-->1584x1224)
zoom_y = 1.33333333
mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
'''
pix是一個Pixmap對象,它(在本例中)包含頁面的RGB圖像,可用于多種用途。
方法Page.get_pixmap()提供了許多用于控制圖像的變體:分辨率、顏色空間(例如,生成灰度圖像或具有減色方案的圖像)、
透明度、旋轉(zhuǎn)、鏡像、移位、剪切等。
例如:創(chuàng)建RGBA圖像(即,包含alpha通道),指定pix=page.get_pixmap(alpha=True)。
Pixmap包含以下引用的許多方法和屬性。其中包括整數(shù)寬度、高度(每個像素)和跨距(一個水平圖像行的字節(jié)數(shù))。
屬性示例表示表示圖像數(shù)據(jù)的矩形字節(jié)區(qū)域(Python字節(jié)對象)。
還可以使用page.get_svg_image()創(chuàng)建頁面的矢量圖像。
'''
pix = page.get_pixmap(matrix=mat, alpha=False)
# 將圖片寫入指定的文件夾內(nèi)
pix.save(image_path + '/' + file_name + '_%s.png' % (pg + 1))
endTime = datetime.datetime.now() # 結(jié)束時間
print('pdf轉(zhuǎn)圖片耗時: %s 秒' % (endTime - startTime).seconds)
print("pdf轉(zhuǎn)圖片成功")
# 返回容器
return [1, '000000', '"pdf轉(zhuǎn)圖片成功', [image_path]]
except Exception as e:
print("pdf轉(zhuǎn)圖片異常," + str(e))
return [0, '999999', "pdf轉(zhuǎn)圖片異常," + str(e), [None]]
def pdf2html(file_path):
'''
@方法名稱: pdf轉(zhuǎn)html
@中文注釋: pdf轉(zhuǎn)html
@入?yún)?
@param file_path str pdf文件路徑
@出參:
@返回狀態(tài):
@return 0 失敗或異常
@return 1 成功
@返回錯誤碼
@返回錯誤信息
@param out_file str html文件名
@作 者: PandaCode輝
@創(chuàng)建時間: 2023-10-16
@使用范例: pdf2html('test.pdf')
'''
try:
if (not type(file_path) is str):
return [0, "111111", "pdf文件路徑參數(shù)類型錯誤,不為字符串", [None]]
# 開始時間
startTime = datetime.datetime.now()
print("pdfPath=" + pdfPath)
# 打開pdf文檔
pdfDoc = fitz.open(pdfPath)
# 提取文件名,去除文件后綴
file_name = pdfPath.split('.')[0]
print(file_name)
out_file = f'{file_name}.html'
print(out_file)
# 打開文件,首次創(chuàng)建寫入
fo = open(out_file, "w+", encoding="utf-8")
# Document.page_count 頁數(shù) (int)
# 循環(huán)頁數(shù)
for pg in range(pdfDoc.page_count):
print('=======%s========' % (pg + 1))
'''
頁面(Page)處理是MuPDF功能的核心。
您可以將頁面呈現(xiàn)為光柵或矢量(SVG)圖像,可以選擇縮放、旋轉(zhuǎn)、移動或剪切頁面。
您可以提取多種格式的頁面文本和圖像,并搜索文本字符串。
對于PDF文檔,可以使用更多的方法向頁面添加文本或圖像。
'''
page = pdfDoc[pg]
'''
提取文本和圖像 page.get_text(opt)
我們還可以以多種不同的形式和細(xì)節(jié)級別提取頁面的所有文本、圖像和其他信息:
對opt使用以下字符串之一以獲取不同的格式:
"text":(默認(rèn))帶換行符的純文本。無格式、無文字位置詳細(xì)信息、無圖像
"blocks":生成文本塊(段落)的列表
"words":生成單詞列表(不包含空格的字符串)
"html":創(chuàng)建頁面的完整視覺版本,包括任何圖像。這可以通過internet瀏覽器顯示
"dict" / "json":與HTML相同的信息級別,但作為Python字典或resp.JSON字符串。
"rawdict" / "rawjson":"dict" / "json"
的超級集合。它還提供諸如XML之類的字符詳細(xì)信息。
"xhtml":文本信息級別與文本版本相同,但包含圖像。
"xml":不包含圖像,但包含每個文本字符的完整位置和字體信息。使用XML模塊進行解釋
'''
# html 格式保存原PDF文本和圖片樣式還行
# text = page.get_text('html')
# xhtml 格式保存原PDF文本和圖片樣式更好
text = page.get_text('xhtml')
# 寫入文件
fo.write(text)
# 關(guān)閉文件
fo.close()
endTime = datetime.datetime.now() # 結(jié)束時間
print('pdf轉(zhuǎn)html耗時: %s 秒' % (endTime - startTime).seconds)
print("pdf轉(zhuǎn)html成功")
# 返回容器
return [1, '000000', '"pdf轉(zhuǎn)html成功', [out_file]]
except Exception as e:
# 關(guān)閉文件
fo.close()
print("pdf轉(zhuǎn)html異常," + str(e))
return [0, '999999', "pdf轉(zhuǎn)html異常," + str(e), [None]]
if __name__ == "__main__":
# PDF地址
pdfPath = 'test.pdf'
# 1,pdf轉(zhuǎn)word
pdf2word(pdfPath)
# 儲存圖片的目錄
imagePath = './images'
# 2,pdf轉(zhuǎn)圖片
pdf2image(pdfPath, imagePath)
# 3,pdf轉(zhuǎn)html
pdf2html(pdfPath)第三步,運行查看效果

到此這篇關(guān)于基于Python實現(xiàn)PDF轉(zhuǎn)換文件格式的文章就介紹到這了,更多相關(guān)Python PDF轉(zhuǎn)換文件格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python結(jié)合shell自動創(chuàng)建kafka的連接器實戰(zhàn)教程
這篇文章主要介紹了python結(jié)合shell自動創(chuàng)建kafka的連接器,需要安裝連接oracle的python包,獲取oracle表信息,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04
TensorFlow實現(xiàn)從txt文件讀取數(shù)據(jù)
今天小編就為大家分享一篇TensorFlow實現(xiàn)從txt文件讀取數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
python利用pandas將excel文件轉(zhuǎn)換為txt文件的方法
今天小編就為大家分享一篇python利用pandas將excel文件轉(zhuǎn)換為txt文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
使用Python實現(xiàn)pdf轉(zhuǎn)圖片再進行OCR識別
這篇文章主要為大家詳細(xì)介紹了如何使用Python實現(xiàn)pdf轉(zhuǎn)圖片再進行OCR識別功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-04-04
Python自動創(chuàng)建Excel并獲取內(nèi)容
這篇文章主要介紹了Python自動創(chuàng)建Excel并獲取內(nèi)容,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09

