python - 如何在 Python 中将 RTF 转换为 Docx

标签 python doxygen docx rtf

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

  • 输入:example.rtf

  • 输出:example.docx

我不想更改任何样式、格式或内容。直接转换一下就可以了。与手动完成的方式相同,通过在 word 中打开 .rtf,然后执行 SaveAs .docx

最佳答案

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

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

  • 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 中获取任何图像并将它们嵌入到生成的 word docx 中,因此不存在外部图像引用依赖项。

关于python - 如何在 Python 中将 RTF 转换为 Docx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65724760/

相关文章:

python - 继续失败的重建索引的简单方法?

python - Bokeh - 从 CustomJS 中访问轴标签会触发错误,但可以在 Python 代码中使用

escaping - 抑制 JAVADOC_AUTOBRIEF 中结束简短描述中的句点

c++ - 如何在 doxygen 中记录生成的构造函数

xml - Docx 或 XPS(或一般的 ooxml)关系转换示例

c# - 有谁知道以编程方式轻松将 PDF 转换为 docx 格式的方法

python - 无法使用 pandas 提取数据框列

Python:如何从给定的键中获取最近的键?

c++ - 在 C++ 中使用 Doxygen 和 GraphViz 的错误调用/调用者图

php - 在 WKWebView 上从服务器读取 docx 文件