【问题标题】:How to convert RTF to Docx in Python如何在 Python 中将 RTF 转换为 Docx
【发布时间】:2021-04-19 19:31:24
【问题描述】:

我正在使用 doxygen 生成 rtf 输出,但我需要使用 python 以自动方式将 rtf 转换为 docx 以在构建系统上运行。

  • 输入:example.rtf

  • 输出:example.docx

我不想更改任何样式、格式或内容。直接转换就行了。与手动打开 .rtf in word 然后执行 SaveAs .docx 的方式相同

【问题讨论】:

    标签: python doxygen docx rtf


    【解决方案1】:

    我花了很多时间和精力来解决这个问题,所以我想我会为社区发布问题和解决方案。最后其实很简单,但是花了很长时间才找到正确的信息来完成。

    此解决方案需要以下内容:

    • Python 3.x
    • PyWin32 模块
    • Windows 10 环境(尚未尝试与其他版本的 Windows 一起使用)
    #convert rtf to docx and embed all pictures in the final document
    def ConvertRtfToDocx(rootDir, file):
        word = win32com.client.Dispatch("Word.Application")
        wdFormatDocumentDefault = 16
        wdHeaderFooterPrimary = 1
        doc = word.Documents.Open(rootDir + "\\" + file)
        for pic in doc.InlineShapes:
            pic.LinkFormat.SavePictureWithDocument = True
        for hPic in doc.sections(1).headers(wdHeaderFooterPrimary).Range.InlineShapes:
            hPic.LinkFormat.SavePictureWithDocument = True
        doc.SaveAs(str(rootDir + "\\refman.docx"), FileFormat=wdFormatDocumentDefault)
        doc.Close()
        word.Quit()
    

    由于 rtf 不能嵌入图像,这也会从 RTF 中获取任何图像并将它们嵌入到生成的单词 docx 中,因此没有外部图像引用依赖项。

    【讨论】:

      【解决方案2】:

      我遇到了与上面类似的问题,所以我想我会发布另一种解决问题的方法:

      您可以使用以下内容将 .rtf(或其他)等文件保存为您能够在 Word 应用程序中保存/打开的任何格式(例如“.docx”、“.rtf”、“.doc”、 '.vcf'、'.txt'、'.odt' 等)

      为此,只需将 new_file_abs 中的“.doc”结尾更改为“.docx”或其他!

      您需要安装 Word。

      (可选我附上如何转换为 .pdf)

      你需要点安装:

      pip install pywin32
      pip install docx2pdf (optional if you need to have pdf)
      

      转换 .rtf -> .doc / 或任何其他 Word 格式。

      from glob import glob
      import re
      import os
      import win32com.client as win32
      from win32com.client import constants
      
      
      def change_word_format(file_path):
          word = win32.gencache.EnsureDispatch('Word.Application')
          doc = word.Documents.Open(file_path)
          doc.Activate()
      
          # Rename path with .doc
          new_file_abs = os.path.abspath(file_path)
          new_file_abs = re.sub(r'\.\w+$', '.doc', new_file_abs)
      
          # Save and Close
          word.ActiveDocument.SaveAs(
              new_file_abs, FileFormat=constants.wdFormatDocument
          )
          doc.Close(False)
      
      
      
      

      如果需要 PDF,则可选 .docx -> .pdf

      from docx2pdf import convert
      
      def docx_to_pdf(ori_file, new_file):
           convert(ori_file, new_file)
          
      

      【讨论】:

      • 这也包含了最终word文档中嵌入的所有图像?
      • @is677 是的。
      • 你知道为什么你必须把它转换成 .doc 和 .docx 吗?
      • 我刚刚注意到您实际上不必执行此额外步骤,也可以直接将其保存到 .docx
      • 我更新了代码,现在应该清楚了
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多