用python把docx批量转为pdf

作者 : admin 本文共692个字,预计阅读时间需要2分钟 发布时间: 2024-06-16 共1人阅读

为保证转换质量,本文的方法是通过脚本和com技术调用office自带的程序进行转换的,因此需要电脑已经装有office。如果希望不装office也能用,则需要研究OpenXML技术,后面实在闲的慌(退休)再搞。

安装所需库

pip install comtypes

示例代码

# Copy from Yue Zhang

import os
import comtypes.client

def convert_word_to_pdf(folder_path):
    word = comtypes.client.CreateObject("Word.Application")
    word.Visible = False

    for file in os.listdir(folder_path):
        if file.endswith(".docx") or file.endswith(".doc"):
            in_file = os.path.abspath(os.path.join(folder_path, file))
            out_file = os.path.abspath(os.path.join(folder_path, file.replace(".docx", ".pdf").replace(".doc", ".pdf")))

            doc = word.Documents.Open(in_file)
            doc.SaveAs(out_file, FileFormat=17) # 17 代表 PDF 格式
            doc.Close()

    word.Quit()

# 使用示例
folder_path = '存放docx或者doc文件的文件夹路径'
convert_word_to_pdf(folder_path)

本站无任何商业行为
个人在线分享 » 用python把docx批量转为pdf
E-->