Python 批量将 Word 转换为 PDF

在这里插入图片描述
大家好,我是水滴~

对于将 Word 文件转换为 PDF 文件,是我们经常需要的工作。单个文件转的话,Word 本身就支持手动转换,但若有大批量的文件需要转换,这种方式还是有不小的工作量。

所以,为了更加便利和高效,我使用 Python 编写了一个批量转换工具,在这里分享给大家。

上面的 GIF 图片就是转换的过程。在使用前,需要安装 pywin32docx2pdf 两个库,下面是详细教程。

安装 pywin32

该库为 Python for Win32(pywin32)扩展的自述文件,它提供了从 Python 访问 Windows API 的权限。

pip install pywin32

安装 docx2pdf

该库可以将 Word 文件转换为 PDF 文件。

pip install docx2pdf

批量转换代码

获取指定目录中所有 docx 文件:

# 获取所有 docx 文件
def get_docx_files(input_path):
    docx_files = list()
    for filename in os.listdir(input_path):
        if filename.endswith(".docx"):
            docx_files.append(filename)
    return docx_files

docx 文件转换为 pdf 文件:

# 将该目录下所有 docx 文件转换为 pdf
def docx2pdf(input_path):
    docx_files = get_docx_files(input_path)
    for docx_file in docx_files:
        print("开始转换 -> " + docx_file)
        convert(input_path + docx_file)

获取源码,请在下方「水滴技术」公众号回复:20230426

猜你喜欢

转载自blog.csdn.net/weixin_67276852/article/details/130413085