Python實(shí)現(xiàn)Word批量轉(zhuǎn)PDF的小工具
前兩天在某魚閑逛,本來想找個(gè)二手機(jī)械鍵盤,結(jié)果刷著刷著突然看到有人在賣——Word 批量轉(zhuǎn) PDF 小工具,還挺火,價(jià)格也不高,但銷量出奇地高,評論里一堆人在夸“好用”、“終于不用一篇篇點(diǎn)了”啥的。
說實(shí)話,當(dāng)時(shí)我人都愣住了——
這個(gè)功能我用 Python 十分鐘能寫完??!
然后我又搜了其它小工具,pdf轉(zhuǎn)Word,Word轉(zhuǎn)圖片,Word加水印什么的……好多
好家伙,花姐以前教大家做的辦公自動(dòng)化小工具原來都能賣錢呀!
那咱今天先復(fù)刻一個(gè)Word 批量轉(zhuǎn) PDF 小工具,順便升級點(diǎn)功能,做個(gè)更絲滑的版本。
保準(zhǔn)你看完就能自己寫個(gè)賣錢去。
思路先擺明:Word 轉(zhuǎn) PDF,其實(shí)沒那么復(fù)雜
你別看這功能聽起來挺“高端”的,其實(shí)本質(zhì)上干的事就是——
把一堆 Word 文檔用程序打開,然后保存為 PDF 格式。
換句話說,這活本質(zhì)就是個(gè)“批處理”。用 Python 來干,簡直再合適不過。
我們需要的工具是 python-docx
?NoNoNo——這個(gè)庫不支持保存為 PDF。真正的主角其實(shí)是:
win32com.client
:用來操作 Word 應(yīng)用(需要 Windows 系統(tǒng)+裝了 Office)- 或者跨平臺一點(diǎn)的玩法,用 LibreOffice + subprocess,不過今天我們先來講講最穩(wěn)最簡單的方式:用 Word 本尊來干活。
上代碼:幾行就能跑起來的 Word 轉(zhuǎn) PDF 腳本
好,開門見山,先上最基礎(chǔ)的版本:
import os import win32com.client def word_to_pdf(input_path, output_path): word = win32com.client.Dispatch("Word.Application") word.Visible = False # 不彈窗,后臺運(yùn)行 doc = word.Documents.Open(input_path) doc.SaveAs(output_path, FileFormat=17) # 17 是 PDF 格式 doc.Close() word.Quit() # 示例用法 word_to_pdf("C:/Users/你的用戶名/Desktop/測試文檔.docx", "C:/Users/你的用戶名/Desktop/測試文檔.pdf")
幾句解釋:
Dispatch("Word.Application")
就是打開 Word 應(yīng)用;FileFormat=17
是告訴它“嘿,我要存成 PDF”;- 結(jié)尾的
Quit()
很重要,不然 Word 可能會(huì)在后臺一直掛著,占資源。 - 如果你電腦里安裝的是WPS,
Dispatch("Word.Application")
這里改成Dispatch("kwps.Application")
,不然會(huì)報(bào)錯(cuò)
是不是很簡單?連我貓都看懂了。
擴(kuò)展:支持批量轉(zhuǎn)換,一次性把一整個(gè)文件夾干掉!
很多人痛苦的點(diǎn)是“文檔太多,一個(gè)個(gè)轉(zhuǎn)太麻煩”。
那好說,我們搞個(gè)批量版本,讓它一口氣全轉(zhuǎn)了:
def batch_convert(folder_path): word = win32com.client.Dispatch("Word.Application") word.Visible = False for file in os.listdir(folder_path): if file.endswith(".doc") or file.endswith(".docx"): doc_path = os.path.join(folder_path, file) pdf_path = os.path.splitext(doc_path)[0] + ".pdf" try: doc = word.Documents.Open(doc_path) doc.SaveAs(pdf_path, FileFormat=17) doc.Close() print(f"? 轉(zhuǎn)換成功:{file}") except Exception as e: print(f"? 轉(zhuǎn)換失?。簕file},原因:{e}") word.Quit()
使用方式:
batch_convert(r"C:\Users\你的用戶名\Desktop\word文件夾")
常見坑點(diǎn),花姐來幫你避一避
寫得簡單不難,難的是兼容和細(xì)節(jié)。
1. 系統(tǒng)必須是 Windows,而且得裝了 MS Office
這玩意底層其實(shí)就是用 COM 調(diào)用了 Word 的功能,所以沒有裝 Word 是用不了的。
2. 文檔里有宏的、被保護(hù)的,可能轉(zhuǎn)不了
有些文檔打開會(huì)彈窗提示宏或者密碼,那個(gè)得手動(dòng)改設(shè)置,程序跑不過去。
3. 文件名不要太長、路徑不要有中文/空格
有時(shí)候路徑太奇怪,Word 會(huì)打不開,轉(zhuǎn)不了,建議統(tǒng)一放到純英文文件夾里。
額外加點(diǎn)料
- 自動(dòng)生成時(shí)間戳文件夾 + 輸出日志
- 自動(dòng)獲取腳本所在目錄下的 Word 文件(不需要用戶手動(dòng)輸路徑)
- 判斷電腦里是否裝了 Office(Word)或 WPS,并自動(dòng)選對的調(diào)用方式
- 打包售賣
生成時(shí)間戳文件夾
def gen_output_folder(): folder = os.path.dirname(os.path.abspath(__file__)) timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") output_folder = os.path.join(folder, f"pdf_{timestamp}") os.makedirs(output_folder, exist_ok=True) return output_folder
自動(dòng)獲取當(dāng)前腳本目錄下的 Word 文件
這太簡單了:
import os def get_word_files_from_current_folder(): folder = os.path.dirname(os.path.abspath(__file__)) word_files = [] for file in os.listdir(folder): if file.endswith(".doc") or file.endswith(".docx"): word_files.append(os.path.join(folder, file)) return word_files
檢測 Office 和 WPS 的方法
我們可以嘗試用 win32com.client.gencache.EnsureDispatch()
去判斷這兩個(gè)程序是否存在。
import win32com.client def detect_office_or_wps(): try: word = win32com.client.gencache.EnsureDispatch("Word.Application") return "office" except: try: wps = win32com.client.gencache.EnsureDispatch("Kwps.Application") return "wps" except: return None
自動(dòng)選擇引擎并批量轉(zhuǎn)換
import os import win32com.client def convert_word_to_pdf_auto(input_path, output_path, engine): if engine == "office": app = win32com.client.Dispatch("Word.Application") elif engine == "wps": app = win32com.client.Dispatch("Kwps.Application") else: print("? 沒有檢測到可用的 Office 或 WPS") return app.Visible = False try: doc = app.Documents.Open(input_path) doc.SaveAs(output_path, FileFormat=17) doc.Close() print(f"? 轉(zhuǎn)換成功:{input_path}") except Exception as e: print(f"? 轉(zhuǎn)換失?。簕input_path},原因:{e}") try: app.Quit() except: print("?? 當(dāng)前環(huán)境不支持 Quit,跳過退出。")
整合所有內(nèi)容,一鍵搞定腳本所在目錄下的所有 Word 文件
def batch_convert_here(): engine = detect_office_or_wps() if not engine: print("?? 系統(tǒng)里沒有安裝 Office 或 WPS,沒法轉(zhuǎn)換") return folder = os.path.dirname(os.path.abspath(__file__)) word_files = get_word_files_from_current_folder() if not word_files: print("???♀? 當(dāng)前文件夾沒有發(fā)現(xiàn) Word 文件") return output_folder = os.path.join(folder, "pdf輸出") os.makedirs(output_folder, exist_ok=True) for word_file in word_files: filename = os.path.splitext(os.path.basename(word_file))[0] pdf_path = os.path.join(output_folder, f"{filename}.pdf") convert_word_to_pdf_auto(word_file, pdf_path, engine) print("?? 所有文件轉(zhuǎn)換完成啦!PDF 都在 'pdf輸出' 文件夾里")
運(yùn)行方式(放在腳本結(jié)尾):
if __name__ == "__main__": batch_convert_here()
做成 EXE 給小白用戶用(pyinstaller)
最后一步,把咱的腳本打包成 .exe
,丟到某魚賣錢(手動(dòng)狗頭)
命令就一句話:
pyinstaller -F word2pdf.py
完整代碼
import os import win32com.client import sys import datetime def get_real_path(): """兼容開發(fā)與打包環(huán)境的路徑獲取""" if getattr(sys, 'frozen', False): base_dir = os.path.dirname(sys.executable) # EXE文件所在目錄[1,7](@ref) else: base_dir = os.path.dirname(os.path.abspath(__file__)) return base_dir # 生成時(shí)間戳文件夾 def gen_output_folder(folder): # folder = os.path.dirname(os.path.abspath(__file__)) timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") output_folder = os.path.join(folder, f"pdf_{timestamp}") os.makedirs(output_folder, exist_ok=True) return output_folder # 自動(dòng)獲取當(dāng)前腳本目錄下的 Word 文件 def get_word_files_from_current_folder(folder): # folder = os.path.dirname(os.path.abspath(__file__)) word_files = [] for file in os.listdir(folder): if file.endswith(".doc") or file.endswith(".docx"): word_files.append(os.path.join(folder, file)) return word_files # 檢測 Office 和 WPS 的方法 def detect_office_or_wps(): try: word = win32com.client.gencache.EnsureDispatch("Word.Application") return "office" except: try: wps = win32com.client.gencache.EnsureDispatch("Kwps.Application") return "wps" except: return None # 自動(dòng)選擇引擎并批量轉(zhuǎn)換 def convert_word_to_pdf_auto(input_path, output_path, engine): if engine == "office": app = win32com.client.Dispatch("Word.Application") elif engine == "wps": app = win32com.client.Dispatch("Kwps.Application") else: print("沒有檢測到可用的 Office 或 WPS") return app.Visible = False try: doc = app.Documents.Open(input_path) doc.SaveAs(output_path, FileFormat=17) doc.Close() print(f"轉(zhuǎn)換成功:{input_path}") except Exception as e: print(f"轉(zhuǎn)換失敗:{input_path},原因:{e}") try: app.Quit() except: print("當(dāng)前環(huán)境不支持 Quit,跳過退出。") # 主函數(shù) def batch_convert_here(): engine = detect_office_or_wps() if not engine: print("系統(tǒng)里沒有安裝 Office 或 WPS,沒法轉(zhuǎn)換") return folder = get_real_path() word_files = get_word_files_from_current_folder(folder) if not word_files: print("當(dāng)前文件夾沒有發(fā)現(xiàn) Word 文件") return output_folder = gen_output_folder(folder) for word_file in word_files: filename = os.path.splitext(os.path.basename(word_file))[0] pdf_path = os.path.join(output_folder, f"{filename}.pdf") convert_word_to_pdf_auto(word_file, pdf_path, engine) print("所有文件轉(zhuǎn)換完成啦!PDF 都在 'output_folder' 文件夾里") if __name__ == "__main__": try: batch_convert_here() print("按 Enter 鍵退出...") input() # 等待用戶按 Enter 鍵 except Exception as e: print(e) print("程序運(yùn)行錯(cuò)誤,按 Enter 鍵退出...") input() # 等待用戶按 Enter 鍵
你可能覺得:“這不就是幾十行代碼嘛,賣這個(gè)會(huì)有人買嗎?”
我一開始也這么想。后來我想通了,某魚上很多買家,根本不懂技術(shù),他們在意的是:
- 能不能一鍵搞定?
- 會(huì)不會(huì)太復(fù)雜?
- 省不省事?
所以啊,寫工具 + 提供說明 + 包裝打包,這些就構(gòu)成了“產(chǎn)品”。
我們程序員有時(shí)候太低估自己的能力了——其實(shí)你隨手寫的腳本,真的能解決很多人的問題。
到此這篇關(guān)于Python實(shí)現(xiàn)Word批量轉(zhuǎn)PDF的小工具的文章就介紹到這了,更多相關(guān)Python Word批量轉(zhuǎn)PDF內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3使用pandas獲取股票數(shù)據(jù)的方法
今天小編就為大家分享一篇python3使用pandas獲取股票數(shù)據(jù)的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12自動(dòng)在Windows中運(yùn)行Python腳本并定時(shí)觸發(fā)功能實(shí)現(xiàn)
講一下在Python中寫好了一個(gè)腳本之后,怎么自動(dòng)雙擊一個(gè)程序自動(dòng)就跑起來。以及,怎么在Windows 10中設(shè)計(jì)定期定時(shí)觸發(fā)并跑腳本,有需要的朋友可以參考下2021-09-09pycharm如何實(shí)現(xiàn)跨目錄調(diào)用文件
這篇文章主要介紹了pycharm如何實(shí)現(xiàn)跨目錄調(diào)用文件,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02詳解Python+OpenCV實(shí)現(xiàn)圖像二值化
圖像二值化就是將圖像上的像素點(diǎn)的灰度值設(shè)置為0或255,也就是將整個(gè)圖像呈現(xiàn)出明顯的黑白效果的過程。本文將通過Python+OpenCV實(shí)現(xiàn)這一過程,感興趣的可以學(xué)習(xí)一下2022-05-05Python應(yīng)用開發(fā)頻繁假死的問題分析及解決
最近在開發(fā)一款自動(dòng)化的應(yīng)用,但是,在測試時(shí),卻發(fā)現(xiàn)了問題,當(dāng)我點(diǎn)擊暫停任務(wù)后,此時(shí)子線程被阻塞,如果我這個(gè)時(shí)候點(diǎn)擊停止,那么就會(huì)任務(wù)結(jié)束,之后,如果我再點(diǎn)擊開始運(yùn)行,整個(gè)應(yīng)用就會(huì)卡死,所以本文介紹了Python應(yīng)用開發(fā)頻繁假死的問題分析及解決,需要的朋友可以參考下2024-08-08