python批量轉(zhuǎn)換word文檔為pdf文件的示例代碼
一、安裝 python-docx 和 comtypes 庫(kù)
在windows命令行窗口執(zhí)行如下代碼:
pip install python-docx pip install comtypes C:\Users\wgx58>pip install python-docx Collecting python-docx Using cached python_docx-1.2.0-py3-none-any.whl.metadata (2.0 kB) Requirement already satisfied: lxml>=3.1.0 in c:\python\lib\site-packages (from python-docx) (6.0.2) Requirement already satisfied: typing_extensions>=4.9.0 in c:\python\lib\site-packages (from python-docx) (4.15.0) Using cached python_docx-1.2.0-py3-none-any.whl (252 kB) Installing collected packages: python-docx Successfully installed python-docx-1.2.0 C:\Users\wgx58>pip install comtypes Collecting comtypes Downloading comtypes-1.4.12-py3-none-any.whl.metadata (7.3 kB) Downloading comtypes-1.4.12-py3-none-any.whl (253 kB) Installing collected packages: comtypes Successfully installed comtypes-1.4.12
二、程序代碼
import os
import comtypes.client
from pathlib import Path
import tkinter as tk
from tkinter import filedialog, messagebox
import threading
class WordToPDFConverter:
def __init__(self):
self.root = tk.Tk()
self.root.title("Word轉(zhuǎn)PDF批量轉(zhuǎn)換器")
self.root.geometry("500x400")
self.setup_ui()
def setup_ui(self):
"""設(shè)置用戶界面"""
# 標(biāo)題
title_label = tk.Label(self.root, text="Word轉(zhuǎn)PDF批量轉(zhuǎn)換器",
font=("Arial", 16, "bold"))
title_label.pack(pady=20)
# 選擇文件夾按鈕
self.select_btn = tk.Button(self.root, text="選擇Word文檔文件夾",
command=self.select_folder,
font=("Arial", 12), bg="#4CAF50", fg="white")
self.select_btn.pack(pady=10)
# 顯示選擇的文件夾
self.folder_label = tk.Label(self.root, text="未選擇文件夾",
font=("Arial", 10), wraplength=400)
self.folder_label.pack(pady=5)
# 輸出文件夾選擇
self.output_btn = tk.Button(self.root, text="選擇PDF輸出文件夾",
command=self.select_output_folder,
font=("Arial", 12), bg="#2196F3", fg="white")
self.output_btn.pack(pady=10)
self.output_label = tk.Label(self.root, text="未選擇輸出文件夾",
font=("Arial", 10), wraplength=400)
self.output_label.pack(pady=5)
# 轉(zhuǎn)換按鈕
self.convert_btn = tk.Button(self.root, text="開始轉(zhuǎn)換",
command=self.start_conversion,
font=("Arial", 14), bg="#FF9800", fg="white",
state="disabled")
self.convert_btn.pack(pady=20)
# 進(jìn)度顯示
self.progress_label = tk.Label(self.root, text="", font=("Arial", 10))
self.progress_label.pack(pady=5)
# 日志文本框
self.log_text = tk.Text(self.root, height=10, width=60)
self.log_text.pack(pady=10, padx=20, fill=tk.BOTH, expand=True)
# 滾動(dòng)條
scrollbar = tk.Scrollbar(self.log_text)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.log_text.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.log_text.yview)
self.input_folder = ""
self.output_folder = ""
def log_message(self, message):
"""添加日志消息"""
self.log_text.insert(tk.END, f"{message}\n")
self.log_text.see(tk.END)
self.root.update()
def select_folder(self):
"""選擇包含Word文檔的文件夾"""
folder = filedialog.askdirectory(title="選擇包含Word文檔的文件夾")
if folder:
self.input_folder = folder
self.folder_label.config(text=f"已選擇: {folder}")
self.check_ready()
def select_output_folder(self):
"""選擇PDF輸出文件夾"""
folder = filedialog.askdirectory(title="選擇PDF輸出文件夾")
if folder:
self.output_folder = folder
self.output_label.config(text=f"已選擇: {folder}")
self.check_ready()
def check_ready(self):
"""檢查是否準(zhǔn)備好轉(zhuǎn)換"""
if self.input_folder and self.output_folder:
self.convert_btn.config(state="normal")
def start_conversion(self):
"""開始轉(zhuǎn)換過程"""
self.convert_btn.config(state="disabled")
thread = threading.Thread(target=self.convert_word_to_pdf)
thread.daemon = True
thread.start()
def convert_word_to_pdf(self):
"""執(zhí)行Word到PDF的轉(zhuǎn)換"""
try:
self.log_message("開始掃描Word文檔...")
# 支持的Word文檔擴(kuò)展名
word_extensions = ['.doc', '.docx', '.docm']
word_files = []
# 遞歸查找所有Word文檔
for root, dirs, files in os.walk(self.input_folder):
for file in files:
if any(file.lower().endswith(ext) for ext in word_extensions):
word_files.append(os.path.join(root, file))
if not word_files:
self.log_message("未找到任何Word文檔!")
self.convert_btn.config(state="normal")
return
self.log_message(f"找到 {len(word_files)} 個(gè)Word文檔")
self.log_message("開始轉(zhuǎn)換...")
success_count = 0
error_count = 0
# 初始化Word應(yīng)用程序
word_app = comtypes.client.CreateObject('Word.Application')
word_app.Visible = False
for i, word_file in enumerate(word_files, 1):
try:
# 更新進(jìn)度
self.progress_label.config(text=f"處理中: {i}/{len(word_files)}")
# 構(gòu)建輸出路徑
relative_path = os.path.relpath(word_file, self.input_folder)
pdf_filename = os.path.splitext(relative_path)[0] + '.pdf'
pdf_path = os.path.join(self.output_folder, pdf_filename)
# 確保輸出目錄存在
os.makedirs(os.path.dirname(pdf_path), exist_ok=True)
# 轉(zhuǎn)換文檔
doc = word_app.Documents.Open(word_file)
doc.SaveAs(pdf_path, FileFormat=17) # 17代表PDF格式
doc.Close()
self.log_message(f"? 成功轉(zhuǎn)換: {os.path.basename(word_file)}")
success_count += 1
except Exception as e:
self.log_message(f"? 轉(zhuǎn)換失敗: {os.path.basename(word_file)} - {str(e)}")
error_count += 1
# 關(guān)閉Word應(yīng)用程序
word_app.Quit()
# 顯示結(jié)果
self.progress_label.config(text="")
self.log_message(f"\n轉(zhuǎn)換完成!")
self.log_message(f"成功: {success_count} 個(gè)文件")
self.log_message(f"失敗: {error_count} 個(gè)文件")
messagebox.showinfo("轉(zhuǎn)換完成",
f"轉(zhuǎn)換完成!\n成功: {success_count} 個(gè)文件\n失敗: {error_count} 個(gè)文件")
except Exception as e:
self.log_message(f"轉(zhuǎn)換過程中發(fā)生錯(cuò)誤: {str(e)}")
messagebox.showerror("錯(cuò)誤", f"轉(zhuǎn)換過程中發(fā)生錯(cuò)誤: {str(e)}")
finally:
self.convert_btn.config(state="normal")
def main():
"""主函數(shù)"""
converter = WordToPDFConverter()
converter.root.mainloop()
if __name__ == "__main__":
main()
三、執(zhí)行程序
執(zhí)行程序后彈出如下窗口,單擊【選擇Word文檔文件夾】選擇word文檔所在的文件夾,單擊【選擇PDF輸出文件夾】選擇存放pdf文檔的文件夾,然后單擊【開始轉(zhuǎn)換】即可:

四、程序特點(diǎn)
1、圖形界面
(1)直觀的GUI界面
(2)實(shí)時(shí)進(jìn)度顯示
(3)詳細(xì)的日志記錄
(4)支持文件夾選擇
2、功能特性
(1)支持多種Word格式(.doc, .docx, .docm)
(2)保持原有文件夾結(jié)構(gòu)
(3)錯(cuò)誤處理和日志記錄
到此這篇關(guān)于python批量轉(zhuǎn)換word文檔為pdf文件的示例代碼的文章就介紹到這了,更多相關(guān)python批量轉(zhuǎn)換word和pdf內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 利用Python實(shí)現(xiàn)文檔格式互轉(zhuǎn)的操作大全(PDF、Word、圖片、Markdown)
- 使用Python輕松實(shí)現(xiàn)Word批量轉(zhuǎn)換為PDF
- Python高效實(shí)現(xiàn)HTML轉(zhuǎn)為Word和PDF
- Python實(shí)現(xiàn)Word轉(zhuǎn)PDF全攻略(從入門到實(shí)戰(zhàn))
- python把pdf轉(zhuǎn)word幾種可行的方法及詳細(xì)步驟
- Python實(shí)現(xiàn)一鍵PDF轉(zhuǎn)Word(附完整代碼及詳細(xì)步驟)
- Python實(shí)現(xiàn)Word批量轉(zhuǎn)PDF的小工具
- Python中PDF轉(zhuǎn)Word的多種實(shí)現(xiàn)方法
相關(guān)文章
Python圖形繪制操作之正弦曲線實(shí)現(xiàn)方法分析
這篇文章主要介紹了Python圖形繪制操作之正弦曲線實(shí)現(xiàn)方法,涉及Python使用numpy模塊數(shù)值運(yùn)算及matplotlib.pyplot模塊進(jìn)行圖形繪制的相關(guān)操作技巧,需要的朋友可以參考下2017-12-12
python激活虛擬環(huán)境(venv)的實(shí)現(xiàn)
本文主要介紹了python激活虛擬環(huán)境(venv)的實(shí)現(xiàn),包括修改PATH環(huán)境變量、設(shè)置VIRTUAL_ENV變量、修改終端提示符、使用虛擬環(huán)境中的python和pip、加載虛擬環(huán)境的依賴等操作,感興趣的可以了解一下2025-05-05
TensorFlow實(shí)現(xiàn)模型斷點(diǎn)訓(xùn)練,checkpoint模型載入方式
這篇文章主要介紹了TensorFlow實(shí)現(xiàn)模型斷點(diǎn)訓(xùn)練,checkpoint模型載入方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2020-05-05
Python實(shí)現(xiàn)將doc轉(zhuǎn)化pdf格式文檔的方法
這篇文章主要介紹了Python實(shí)現(xiàn)將doc轉(zhuǎn)化pdf格式文檔的方法,結(jié)合實(shí)例形式分析了Python實(shí)現(xiàn)doc格式文件讀取及轉(zhuǎn)換pdf格式文件的操作技巧,以及php調(diào)用py文件的具體實(shí)現(xiàn)方法,需要的朋友可以參考下2018-01-01
python中Celery 異步任務(wù)隊(duì)列的高級(jí)用法
Celery 是一個(gè)高效且可擴(kuò)展的任務(wù)隊(duì)列框架,通過合理配置任務(wù)重試、分組工作流、優(yōu)先級(jí)管理以及監(jiān)控工具,可以顯著提升系統(tǒng)的可靠性和性能,感興趣的可以了解一下2025-09-09
使用Python的Twisted框架編寫非阻塞程序的代碼示例
Twisted是基于異步模式的開發(fā)框架,因而利用Twisted進(jìn)行非阻塞編程自然也是必會(huì)的用法,下面我們就來(lái)一起看一下使用Python的Twisted框架編寫非阻塞程序的代碼示例:2016-05-05
python 獲取sqlite3數(shù)據(jù)庫(kù)的表名和表字段名的實(shí)例
今天小編就為大家分享一篇python 獲取sqlite3數(shù)據(jù)庫(kù)的表名和表字段名的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2019-07-07

