2015-05-27 100 views
7

我使用Word 2013自动创建一个报告为docx,然后将其保存为pdf格式。Pywin32保存.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)

是否有人有一个想法,为什么它不工作?

+0

为什么不使用reportlab创建报告?然后它全部用Python,你不必担心这些转换问题。 –

回答

3

有几个不错的库来处理这个任务:

也有在此ActiveState的食谱做exactly this的例子Convert Microsoft Word files to PDF with DOCXtoPDF


如果坚持上使用Windows API(S)也有通过win32com在这个配方这样的例子Convert doc and docx files to pdf


可以也做到这一点使用comtypes感谢.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() 
+0

嗨,詹姆斯,感谢您的回答和您的建议!我已经尝试过使用comtypes和ActiveState的例子,但不幸的是,它在保存部分创建了与上面相同的问题。 至于python-docx,它不允许将它保存为pdf [文档](https://github.com/python-openxml/python-docx/issues/113),并且所有其他库不会似乎采取了docx标题。 – RenShan