[英]How to convert RTF to Docx in Python
我正在使用 doxygen 生成 rtf output,但我需要使用 python 以自动方式将 rtf 转换为 docx 以在构建系统上运行。
输入:example.rtf
Output:example.docx
我不想更改任何样式、格式或内容。 直接转换就行了。 与手动打开 word 中的 .rtf 然后执行 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 中,因此没有外部图像引用依赖项。
convert.rtf ->.doc ->.docx 对我有用(可选地,我附上了第 3 步以转换为.pdf)
您需要 pip 安装:
pip install pywin32
pip install docx2pdf (optional if you need to have pdf)
第 1 步:转换.rtf -> .doc
from glob import glob
import re
import os
import win32com.client as win32
from win32com.client import constants
def rtf_to_doc(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)
第 2 步:转换.doc -> .docx
import re
import os
from win32com.client import constants
import win32com.client as win32
def doc_to_docx(file_path):
word = win32.gencache.EnsureDispatch('Word.Application')
doc = word.Documents.Open(file_path)
doc.Activate()
# Rename path with .docx
new_file_abs = os.path.abspath(file_path)
new_file_abs = re.sub(r'\.\w+$', '.docx', new_file_abs)
# Save and Close
word.ActiveDocument.SaveAs(
new_file_abs, FileFormat=constants.wdFormatXMLDocument
)
doc.Close(False)
第 3 步(如果需要 PDF,则可选).docx ->.pdf
from docx2pdf import convert
def docx_to_pdf(ori_file, new_file):
convert(ori_file, new_file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.