Python Pywin32将.docx另存为pdf
我正在使用Word 2013自动将报告创建为docx,然后将其保存为pdf格式 但是,当我调用函数SaveAs2()时,脚本弹出“另存为”窗口并引发此异常:Python Pywin32将.docx另存为pdf,python,pywin32,word-2013,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) 以下是我要打开并另存为新文件的代码: self.path = os.path.abspath(
(-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)
我用的是:
使用pywin32的python2.7(构建219)
有人知道为什么它不起作用吗?有几个很好的库可以处理这个任务:
如果您坚持使用Windows API,本配方中还有一个通过
win32com
实现此目的的示例
您也可以使用(感谢) 示例:
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()
看来“Office 2013”是瓶颈
我在使用Word 2013(“Office 2013”)时遇到了同样的问题,但是,当我尝试使用“Office 365”和“Office 2010”运行您的代码段时,它可以运行 我现在可以推荐两种解决方案:
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()
- 尝试不同的MS Office版本(365和2010已测试)
- 使用一些在线API-s将其转换为PDF
更改模块/库不会解决此问题,
只有正确的Office版本才会出现。嗨,詹姆斯,谢谢你的回答和建议!我已经用comtypes和ActiveState尝试了您的示例,但不幸的是,它在保存部分产生了与上面相同的问题。至于PythonDocx,它不允许将其保存为pdf[document](),而且所有其他库似乎都不采用docx头。James,PythonDocx库很好(已经在使用它),但不能用于生成pdf。您需要一个“渲染器”来实现这一点。为什么不使用reportlab创建报表呢?然后,一切都在Python中,您不必担心这些转换问题。