Pywin32将.docx保存为pdf

Ren*_*han 9 python pywin32 word-2013

我正在使用Word 2013自动创建一个报告作为docx,然后将其保存为pdf格式.

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

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

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

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)
Run Code Online (Sandbox Code Playgroud)

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

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

Jam*_*lls 5

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

在此ActiveState食谱中也有一个完全做到这一点的示例,使用DOCXtoPDF将Microsoft Word文件转换为PDF


如果您坚持使用Windows API,那么win32com在此配方中还有一个通过doc和docx文件转换为pdf的示例。


可能也做到这一点使用comtypes由于.DOC使用PDF格式的python

例:

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()
Run Code Online (Sandbox Code Playgroud)

  • 嗨,詹姆斯,谢谢您的回答和建议!我已经用comtypes和ActiveState尝试了您的示例,但是不幸的是,在保存部分期间,它产生了与上述相同的麻烦。至于python-docx,不允许将其另存为pdf [document](https://github.com/python-openxml/python-docx/issues/113),而所有其他库似乎都没有获取docx标头。 (2认同)