python
import os
from win32com.client import Dispatch
def convert_doc_to_pdf(doc_path, pdf_path):
try:
# 创建Word应用实例
word = Dispatch('Word.Application')
# 设置Word不可见
word.Visible = False
# 设置不显示警告
word.DisplayAlerts = False
# 确保路径是绝对路径
doc_path = os.path.abspath(doc_path)
pdf_path = os.path.abspath(pdf_path)
# 打开文档
doc = word.Documents.Open(doc_path)
# 保存为PDF
doc.SaveAs(pdf_path, FileFormat=17) # 17代表PDF格式
doc.Close()
print(f"成功转换: {doc_path} -> {pdf_path}")
except Exception as e:
print(f"转换失败 {doc_path}: {str(e)}")
finally:
word.Quit()
# 批量转换
folder_path = r"C:\Users\demo\Desktop\11.3-word类\11.3-word类"
for file in os.listdir(folder_path):
if file.endswith((".doc", ".docx")):
input_path = os.path.join(folder_path, file)
output_path = os.path.join(folder_path, file.rsplit('.', 1)[0] + ".pdf")
convert_doc_to_pdf(input_path, output_path)