Python實現Word批量轉PDF的小工具
前兩天在某魚閑逛,本來想找個二手機械鍵盤,結果刷著刷著突然看到有人在賣——Word 批量轉 PDF 小工具,還挺火,價格也不高,但銷量出奇地高,評論里一堆人在夸“好用”、“終于不用一篇篇點了”啥的。
說實話,當時我人都愣住了——
這個功能我用 Python 十分鐘能寫完?。?/strong>
然后我又搜了其它小工具,pdf轉Word,Word轉圖片,Word加水印什么的……好多
好家伙,花姐以前教大家做的辦公自動化小工具原來都能賣錢呀!
那咱今天先復刻一個Word 批量轉 PDF 小工具,順便升級點功能,做個更絲滑的版本。
保準你看完就能自己寫個賣錢去。
思路先擺明:Word 轉 PDF,其實沒那么復雜
你別看這功能聽起來挺“高端”的,其實本質上干的事就是——
把一堆 Word 文檔用程序打開,然后保存為 PDF 格式。
換句話說,這活本質就是個“批處理”。用 Python 來干,簡直再合適不過。
我們需要的工具是 python-docx
?NoNoNo——這個庫不支持保存為 PDF。真正的主角其實是:
win32com.client
:用來操作 Word 應用(需要 Windows 系統(tǒng)+裝了 Office)- 或者跨平臺一點的玩法,用 LibreOffice + subprocess,不過今天我們先來講講最穩(wěn)最簡單的方式:用 Word 本尊來干活。
上代碼:幾行就能跑起來的 Word 轉 PDF 腳本
好,開門見山,先上最基礎的版本:
import os import win32com.client def word_to_pdf(input_path, output_path): word = win32com.client.Dispatch("Word.Application") word.Visible = False # 不彈窗,后臺運行 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 應用;FileFormat=17
是告訴它“嘿,我要存成 PDF”;- 結尾的
Quit()
很重要,不然 Word 可能會在后臺一直掛著,占資源。 - 如果你電腦里安裝的是WPS,
Dispatch("Word.Application")
這里改成Dispatch("kwps.Application")
,不然會報錯
是不是很簡單?連我貓都看懂了。
擴展:支持批量轉換,一次性把一整個文件夾干掉!
很多人痛苦的點是“文檔太多,一個個轉太麻煩”。
那好說,我們搞個批量版本,讓它一口氣全轉了:
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"? 轉換成功:{file}") except Exception as e: print(f"? 轉換失敗:{file},原因:{e}") word.Quit()
使用方式:
batch_convert(r"C:\Users\你的用戶名\Desktop\word文件夾")
常見坑點,花姐來幫你避一避
寫得簡單不難,難的是兼容和細節(jié)。
1. 系統(tǒng)必須是 Windows,而且得裝了 MS Office
這玩意底層其實就是用 COM 調用了 Word 的功能,所以沒有裝 Word 是用不了的。
2. 文檔里有宏的、被保護的,可能轉不了
有些文檔打開會彈窗提示宏或者密碼,那個得手動改設置,程序跑不過去。
3. 文件名不要太長、路徑不要有中文/空格
有時候路徑太奇怪,Word 會打不開,轉不了,建議統(tǒng)一放到純英文文件夾里。
額外加點料
- 自動生成時間戳文件夾 + 輸出日志
- 自動獲取腳本所在目錄下的 Word 文件(不需要用戶手動輸路徑)
- 判斷電腦里是否裝了 Office(Word)或 WPS,并自動選對的調用方式
- 打包售賣
生成時間戳文件夾
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
自動獲取當前腳本目錄下的 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()
去判斷這兩個程序是否存在。
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
自動選擇引擎并批量轉換
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"? 轉換成功:{input_path}") except Exception as e: print(f"? 轉換失?。簕input_path},原因:{e}") try: app.Quit() except: print("?? 當前環(huán)境不支持 Quit,跳過退出。")
整合所有內容,一鍵搞定腳本所在目錄下的所有 Word 文件
def batch_convert_here(): engine = detect_office_or_wps() if not engine: print("?? 系統(tǒng)里沒有安裝 Office 或 WPS,沒法轉換") return folder = os.path.dirname(os.path.abspath(__file__)) word_files = get_word_files_from_current_folder() if not word_files: print("???♀? 當前文件夾沒有發(fā)現 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("?? 所有文件轉換完成啦!PDF 都在 'pdf輸出' 文件夾里")
運行方式(放在腳本結尾):
if __name__ == "__main__": batch_convert_here()
做成 EXE 給小白用戶用(pyinstaller)
最后一步,把咱的腳本打包成 .exe
,丟到某魚賣錢(手動狗頭)
命令就一句話:
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 # 生成時間戳文件夾 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 # 自動獲取當前腳本目錄下的 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 # 自動選擇引擎并批量轉換 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"轉換成功:{input_path}") except Exception as e: print(f"轉換失?。簕input_path},原因:{e}") try: app.Quit() except: print("當前環(huán)境不支持 Quit,跳過退出。") # 主函數 def batch_convert_here(): engine = detect_office_or_wps() if not engine: print("系統(tǒng)里沒有安裝 Office 或 WPS,沒法轉換") return folder = get_real_path() word_files = get_word_files_from_current_folder(folder) if not word_files: print("當前文件夾沒有發(fā)現 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("所有文件轉換完成啦!PDF 都在 'output_folder' 文件夾里") if __name__ == "__main__": try: batch_convert_here() print("按 Enter 鍵退出...") input() # 等待用戶按 Enter 鍵 except Exception as e: print(e) print("程序運行錯誤,按 Enter 鍵退出...") input() # 等待用戶按 Enter 鍵
你可能覺得:“這不就是幾十行代碼嘛,賣這個會有人買嗎?”
我一開始也這么想。后來我想通了,某魚上很多買家,根本不懂技術,他們在意的是:
- 能不能一鍵搞定?
- 會不會太復雜?
- 省不省事?
所以啊,寫工具 + 提供說明 + 包裝打包,這些就構成了“產品”。
我們程序員有時候太低估自己的能力了——其實你隨手寫的腳本,真的能解決很多人的問題。
到此這篇關于Python實現Word批量轉PDF的小工具的文章就介紹到這了,更多相關Python Word批量轉PDF內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
自動在Windows中運行Python腳本并定時觸發(fā)功能實現
講一下在Python中寫好了一個腳本之后,怎么自動雙擊一個程序自動就跑起來。以及,怎么在Windows 10中設計定期定時觸發(fā)并跑腳本,有需要的朋友可以參考下2021-09-09