python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Word批量转PDF

Python实现Word批量转PDF的小工具

作者:花小姐的春天

这篇文章主要为大家详细介绍了如何使用Python复刻一个Word批量转PDF的小工具,文中的示例代码讲解详细,感兴趣的小伙伴可以参考一下

前两天在某鱼闲逛,本来想找个二手机械键盘,结果刷着刷着突然看到有人在卖——Word 批量转 PDF 小工具,还挺火,价格也不高,但销量出奇地高,评论里一堆人在夸“好用”、“终于不用一篇篇点了”啥的。

说实话,当时我人都愣住了——

这个功能我用 Python 十分钟能写完啊!

然后我又搜了其它小工具,pdf转Word,Word转图片,Word加水印什么的……好多

好家伙,花姐以前教大家做的办公自动化小工具原来都能卖钱呀!

那咱今天先复刻一个Word 批量转 PDF 小工具,顺便升级点功能,做个更丝滑的版本。

保准你看完就能自己写个卖钱去。

思路先摆明:Word 转 PDF,其实没那么复杂

你别看这功能听起来挺“高端”的,其实本质上干的事就是——

把一堆 Word 文档用程序打开,然后保存为 PDF 格式。

换句话说,这活本质就是个“批处理”。用 Python 来干,简直再合适不过。

我们需要的工具是 python-docx?NoNoNo——这个库不支持保存为 PDF。真正的主角其实是:

上代码:几行就能跑起来的 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")

几句解释:

是不是很简单?连我猫都看懂了。

扩展:支持批量转换,一次性把一整个文件夹干掉!

很多人痛苦的点是“文档太多,一个个转太麻烦”。

那好说,我们搞个批量版本,让它一口气全转了:

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文件夹")

常见坑点,花姐来帮你避一避

写得简单不难,难的是兼容和细节

1. 系统必须是 Windows,而且得装了 MS Office

这玩意底层其实就是用 COM 调用了 Word 的功能,所以没有装 Word 是用不了的。

2. 文档里有宏的、被保护的,可能转不了

有些文档打开会弹窗提示宏或者密码,那个得手动改设置,程序跑不过去。

3. 文件名不要太长、路径不要有中文/空格

有时候路径太奇怪,Word 会打不开,转不了,建议统一放到纯英文文件夹里。

额外加点料

生成时间戳文件夹

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("⚠️ 当前环境不支持 Quit,跳过退出。")

整合所有内容,一键搞定脚本所在目录下的所有 Word 文件

def batch_convert_here():
    engine = detect_office_or_wps()
    if not engine:
        print("😭 系统里没有安装 Office 或 WPS,没法转换")
        return

    folder = os.path.dirname(os.path.abspath(__file__))
    word_files = get_word_files_from_current_folder()

    if not word_files:
        print("🤷‍♀️ 当前文件夹没有发现 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():
    """兼容开发与打包环境的路径获取"""
    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("当前环境不支持 Quit,跳过退出。")

# 主函数  
def batch_convert_here():
    engine = detect_office_or_wps()
    if not engine:
        print("系统里没有安装 Office 或 WPS,没法转换")
        return

    folder = get_real_path()
    word_files = get_word_files_from_current_folder(folder)
    

    if not word_files:
        print("当前文件夹没有发现 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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文