Pywin32 将 .docx 保存为 pdf

问题描述 投票:0回答:3

我使用 Word 2013 自动创建 docx 格式的报告,然后将其另存为 pdf 格式。

但是当我调用函数 SaveAs2() 时,脚本会弹出“另存为”窗口并抛出此异常:

(-2147352567, 'Exception occurred.', (0, u'Microsoft Word', u'Command failed', u'wdmain11.chm', 36966, -2146824090), None)

这是我打开并保存为新文件的代码:

self.path = os.path.abspath(path)

self.wordApp = win32.Dispatch('Word.Application')  #create a word application object
self.wordApp.Visible = False  # if false hide the word application (app does't open but still usable)

self.document = self.wordApp.Documents.Open(self.path + "/" + documentRef)  # opening the template file



absFileName = "D:\\test.pdf"
        self.document.SaveAs2(FileName=absFileName,FileFormat=17)

我正在使用: python2.7 与 pywin32 (build 219)

有人知道为什么它不起作用吗?

python pywin32 word-2013
3个回答
5
投票

有几个不错的库可以处理此任务:

此 ActiveState Recipe 中还有一个执行正是这样做的示例 使用 DOCXtoPDF 将 Microsoft Word 文件转换为 PDF


如果您坚持使用Windows API,本食谱中还有一个通过

win32com
执行此操作的示例将doc和docx文件转换为pdf


也可以使用

comtypes
感谢使用python.doc转为pdf)

示例:

import os
import sys


import comtypes.client


wdFormatPDF = 17


def covx_to_pdf(infile, outfile):
    """Convert a Word .docx to PDF"""

    word = comtypes.client.CreateObject('Word.Application')
    doc = word.Documents.Open(infile)
    doc.SaveAs(outfile, FileFormat=wdFormatPDF)
    doc.Close()
    word.Quit()

1
投票

使用这个,别忘了像这样安装win32:

pip install pywin32

将doc转换为pdf的功能是这样的:

import win32com.client as win32  
def convert_to_pdf(doc):
    """Convert given word document to pdf"""
    word = win32.DispatchEx("Word.Application")
    new_name = doc.replace(".docx", r".pdf")
    worddoc = word.Documents.Open(doc)
    worddoc.SaveAs(new_name, FileFormat=17)
    worddoc.Close()
    return None

path_to_word_document = os.path.join(os.getcwd(), 'report_1.docx')
convert_to_pdf(path_to_word_document)

给我我的开始,我真的需要它:-) 有关更多信息,请查找库中的文档 https://pypi.org/project/pywin32/


1
投票

Office 2013”导致了这个问题

我在使用 Word 2013(“Office 2013”)时遇到同样的问题,
但是当我尝试使用“Office 365”和“Office 2010”运行您的代码片段时,它有效

我现在可以推荐两种解决方案:

  • 尝试不同的 MS Office 版本(已测试 365 和 2010)
  • 使用一些在线API将其转换为PDF

注:
更改模块/库无法解决问题,
只有正确的 Office 版本才可以。

© www.soinside.com 2019 - 2024. All rights reserved.