【发布时间】:2021-04-19 19:31:24
【问题描述】:
我正在使用 doxygen 生成 rtf 输出,但我需要使用 python 以自动方式将 rtf 转换为 docx 以在构建系统上运行。
-
输入:example.rtf
-
输出:example.docx
我不想更改任何样式、格式或内容。直接转换就行了。与手动打开 .rtf in word 然后执行 SaveAs .docx 的方式相同
【问题讨论】:
我正在使用 doxygen 生成 rtf 输出,但我需要使用 python 以自动方式将 rtf 转换为 docx 以在构建系统上运行。
输入:example.rtf
输出:example.docx
我不想更改任何样式、格式或内容。直接转换就行了。与手动打开 .rtf in word 然后执行 SaveAs .docx 的方式相同
【问题讨论】:
我花了很多时间和精力来解决这个问题,所以我想我会为社区发布问题和解决方案。最后其实很简单,但是花了很长时间才找到正确的信息来完成。
此解决方案需要以下内容:
#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 中,因此没有外部图像引用依赖项。
【讨论】:
我遇到了与上面类似的问题,所以我想我会发布另一种解决问题的方法:
您可以使用以下内容将 .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)
【讨论】: