Python办公自动化:调用Word实现批量DOC转PDF,保留原格式,一键搞定!
前言前面两篇文章我们分别实现了 PDF转图片 和 PPT转PDF今天带来办公自动化三部曲的最后一环——Word批量转PDF。你是否遇到过这些场景收集了十几个同事的Word文档需要统一转成PDF发给客户防止排版错乱论文、标书需要以PDF格式提交但Word版本众多一个个打开另存为太耗时希望保留Word中的书签、目录结构PDF中能自动生成导航。今天我就用 Python 的pywin32调用 Microsoft Word 的 COM 接口来快速实现批量转换不仅保留原始排版连书签都能完美带过来。而且代码完全动态路径放在任何文件夹都能直接运行。目录一、安装依赖库1.1 实现原理二、 代码逐段精讲2.1 动态路径——用完即走无需配置2.2 核心转换函数 ExportAsFixedFormat2.3跳过已存在的 PDF三、避坑指南 总结一、安装依赖库左下角打开Python终端使用阿里云镜像快速安装pip install pywin32 -i https://mirrors.aliyun.com/pypi/simple/pywin32是 Python 调用 Windows API 和 COM 组件的桥梁我们通过它来控制 Word 应用程序。1.1 实现原理# -*- coding: utf-8 -*- Python批量将Word文件DOC/DOCX转为PDF文件 功能自动识别当前目录下所有Word文档调用本地Word转为PDF #pip install pywin32 -i https://mirrors.aliyun.com/pypi/simple/ 安装包 import os #导入内置系统的模块用来遍历文件架里的所有文件。 from win32com.client import Dispatch, constants, gencache #导入第三方软件库的工具 def doc2pdf(word_file, pdf_file): 单个Word转PDF word_file: Word文件完整路径 pdf_file: 输出PDF完整路径 word gencache.EnsureDispatch(Word.Application) doc word.Documents.Open(word_file, ReadOnly1) # 导出为PDF关键参数 doc.ExportAsFixedFormat(pdf_file, constants.wdExportFormatPDF, Itemconstants.wdExportDocumentWithMarkup, CreateBookmarksconstants.wdExportCreateHeadingBookmarks) word.Quit(constants.wdDoNotSaveChanges) print(f✅ 转换成功{os.path.basename(word_file)} → {os.path.basename(pdf_file)}) def convert_word_in_folder(input_dir, output_dir): 批量转换文件夹内所有Word文档 input_dir: 包含Word文件的目录 output_dir: PDF输出目录 if not os.path.exists(input_dir): print(f❌ 输入目录不存在{input_dir}) return files os.listdir(input_dir) # 不区分大小写过滤 .doc 和 .docx word_files [f for f in files if f.lower().endswith((.doc, .docx))] if not word_files: print(❌ 未找到任何Word文档.doc 或 .docx) return os.makedirs(output_dir, exist_okTrue) print(f 找到 {len(word_files)} 个Word文件开始转换...) for word_file in word_files: full_input os.path.join(input_dir, word_file) base_name os.path.splitext(word_file)[0] .pdf full_output os.path.join(output_dir, base_name) # 跳过已存在的PDF避免重复转换 if os.path.exists(full_output): print(f⏭️ 已跳过文件已存在{base_name}) continue try: doc2pdf(full_input, full_output) except Exception as e: print(f❌ 转换 {word_file} 时出错{e}) print( 所有Word文档转换完成) if __name__ __main__: # ---------- 全部使用动态路径 ---------- script_dir os.path.dirname(os.path.abspath(__file__)) # 输入目录默认使用脚本所在目录把你的Word文档放这里 docpath script_dir # 输出目录在脚本所在目录下新建 pdf_output 文件夹 pdfpath os.path.join(script_dir, pdf_output) convert_word_in_folder(docpath, pdfpath)二、 代码逐段精讲2.1 动态路径——用完即走无需配置script_dir os.path.dirname(os.path.abspath(__file__)) docpath script_dir pdfpath os.path.join(script_dir, pdf_output)还是老规矩脚本在哪它就在哪工作。输出的 PDF 统一放在pdf_output子文件夹干净整洁。2.2 核心转换函数ExportAsFixedFormatdoc.ExportAsFixedFormat(pdf_file, constants.wdExportFormatPDF, Itemconstants.wdExportDocumentWithMarkup, CreateBookmarksconstants.wdExportCreateHeadingBookmarks)这是 Word 自带的导出方法参数含义wdExportFormatPDF输出 PDF 格式值17ItemwdExportDocumentWithMarkup导出包含批注的文档可改为wdExportDocumentContent只导正文CreateBookmarkswdExportCreateHeadingBookmarks为标题自动生成书签PDF 左侧导航栏你甚至可以改为constants.wdExportFormatXPS输出 XPS 格式灵活多变。2.3跳过已存在的 PDFif os.path.exists(full_output): print(f⏭️ 已跳过文件已存在{base_name}) continue如果中途运行中断再次执行时不会重复转换省时省力。三、避坑指南ImportError: No module named win32com.client原因pywin32未安装或安装不完整。解决方案重新安装pip install --upgrade pywin32 -i https://mirrors.aliyun.com/pypi/simple/然后重启 Python 环境。 总结通过不到 60 行 Python 代码我们利用系统自带的 Microsoft Word 实现了 Word 批量转 PDF。它✅ 完美保留原文档格式字体、段落、表格、图片✅ 自动生成书签方便 PDF 导航✅ 动态路径随放随用✅ 支持.doc和.docx双格式至此我们完成了办公自动化文档转换三部曲PDF → 图片PyMuPDFPPT → PDFcomtypesWord → PDFpywin32三篇文章相辅相成覆盖了日常办公最常用的文档格式转换需求。赶紧收藏备用吧如果运行中遇到任何问题特别是环境配置相关的报错欢迎在评论区留言我会第一时间解答。如果觉得有帮助请点赞、收藏、转发三连支持一下~