Pywin32另存.docx为pd

2024-04-27 00:09:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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(构建219)

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


Tags: thepath函数selfpdfapplication格式报告
1条回答
网友
1楼 · 发布于 2024-04-27 00:09:41

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

还有一个在这个ActiveState配方中执行exactly this的示例Convert Microsoft Word files to PDF with DOCXtoPDF


如果您坚持使用Windows API,还有一个例子可以通过这个配方中的win32com来实现


你也可以使用^{}感谢.doc to pdf using 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()

相关问题 更多 >