[Python] 纯文本查看 复制代码
import comtypes.client
import os
from datetime import datetime
def convert_word_to_pdf_comtypes(word_file, pdf_file):
try:
word = comtypes.client.CreateObject('Word.Application')
word.Visible = False
doc = word.Documents.Open(word_file)
doc.SaveAs(pdf_file, FileFormat=17) # 17 代表 PDF 格式
doc.Close()
word.Quit()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"{timestamp} 成功将 {word_file} 转换为 {pdf_file}")
except Exception as e:
print(f"转换 {word_file} 失败: {e}")
def batch_convert_word_to_pdf(folder_path):
if not os.path.exists(folder_path):
print(f"错误:文件夹路径 '{folder_path}' 不存在。")
return
for filename in os.listdir(folder_path):
if filename.endswith(('.doc', '.docx')):
word_file = os.path.join(folder_path, filename)
pdf_file = os.path.join(folder_path, os.path.splitext(filename)[0] + ".pdf")
convert_word_to_pdf_comtypes(word_file, pdf_file)
if __name__ == "__main__":
folder_path = r"D:\Documents\test" # 替换为你的 Word 文件夹路径
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(timestamp + " 开始处理")
batch_convert_word_to_pdf(folder_path)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(timestamp + " 全部处理完毕!") |