Python实现将word有效转为pdf文件

引用库文件

import comtypes.client

import pythoncom

实现代码

def convertToPdf(word_file_path, word_error):     #word_file_path:word文件路径、word_error:错误信息,可自定义是否需要
    pythoncom.CoInitialize()        #必须有此初始化操作,否则comtypes.client.CreateObjec会出现偶发性调用失败的情况
    try:
        word = comtypes.client.CreateObject('Word.Application')        #创建word对象
        try:
            doc = word.Documents.Open(word_file_path)        #打开word文件
            output_file = word_file_path.rsplit('.', 1)[0] + ".pdf"
            doc.SaveAs(output_file, FileFormat=17)                #生成pdf
            doc.Close()
            word.Visible = False
        finally:
            word.Quit()
            pythoncom.CoUninitialize()
    except Exception as e:
        word_error.m_wordErrorType = WordErrorType.WET_ConvertToPDFError
        word_error.m_message = "Failed to convert Word to PDF"
        traceback.print_exc()
    return word_error

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值