【问题标题】:Pywin32 save .docx as pdfPywin32 将 .docx 保存为 pdf
【发布时间】:2015-08-09 11:03:21
【问题描述】:

我正在使用 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)

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

【问题讨论】:

  • 为什么不直接使用reportlab 创建报告?然后一切都在 Python 中,您不必担心这些转换问题。

标签: python pywin32 word-2013


【解决方案1】:

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

在这个 ActiveState Recipe Convert Microsoft Word files to PDF with DOCXtoPDF 中还有一个做exactly this 的例子


如果您坚持使用 Windows API,则在此配方 Convert doc and docx files to pdf 中还有一个通过 win32com 执行此操作的示例@


可以也可以使用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()

【讨论】:

  • 嗨,詹姆斯,感谢您的回答和建议!我已经用 comtypes 和 ActiveState 尝试了你的例子,但不幸的是,它在保存部分产生了与上面相同的问题。至于 python-docx,它不允许将其保存为 pdf [文档](github.com/python-openxml/python-docx/issues/113),并且所有其他库似乎都没有采用 docx 标头。
  • James,python-docx 库很棒(已经在使用它)但不能用于生成 PDF。你需要一个“渲染器”才能做到这一点。
【解决方案2】:

看起来“Office 2013”​​是瓶颈。

我在使用 Word 2013(“Office 2013”​​)时遇到了同样的问题,
但是当我尝试使用“Office 365”和“Office 2010”运行您的代码 sn-p 时,它可以工作

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

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

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

【讨论】:

    【解决方案3】:

    使用这个,别忘了这样安装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/

    【讨论】:

      猜你喜欢
      • 2012-08-16
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 2018-08-22
      相关资源
      最近更新 更多