用python把docx批量转为pdf

为保证转换质量,本文的方法是通过脚本和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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值