我使用 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/