You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何批量将RTF文件转换为HTML并保留文本颜色及格式?

批量RTF转HTML并保留文本颜色的解决方案

问题背景

需要批量将指定文件夹下的RTF文件转换为HTML,要求尽可能保留原有格式;现有Python脚本可完成转换,但无法保留RTF中的文本颜色。

核心原因

现有脚本通过「RTF转DOCX再用mammoth转HTML」的流程实现,但mammoth默认仅支持基础格式转换,对文本颜色这类样式无默认处理逻辑;同时中转DOCX的步骤也可能丢失部分格式信息。

解决方案

方案一:直接通过Word COM对象转HTML(推荐)

跳过DOCX中转步骤,直接调用Word的原生转换能力将RTF另存为HTML,能最大程度保留文本颜色、字体、段落等原有格式。

修改后的完整代码:

import os
import win32com.client as win32
from win32com.client import constants
import sys

def convert_rtf_to_html_directly(input_rtf):
    word = win32.gencache.EnsureDispatch('Word.Application')
    word.Visible = False  # 后台运行,不显示Word窗口
    try:
        doc = word.Documents.Open(input_rtf)
        output_html = os.path.splitext(input_rtf)[0] + ".html"
        # 用过滤式HTML格式保存,保留完整样式
        doc.SaveAs(
            output_html,
            FileFormat=constants.wdFormatFilteredHTML
        )
        doc.Close(False)
        return output_html
    finally:
        word.Quit()  # 确保Word进程退出

def convert_rtf_files_to_html(start_path):
    for root, dirs, files in os.walk(start_path):
        for file in files:
            if file.endswith(".rtf"):
                input_rtf = os.path.join(root, file)
                try:
                    output_html_path = convert_rtf_to_html_directly(input_rtf)
                    print(f"转换完成:{input_rtf} -> {output_html_path}")
                    # 可选:删除原RTF文件,按需开启
                    # os.remove(input_rtf)
                except Exception as e:
                    print(f"转换失败 {input_rtf}: {str(e)}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("用法:python script.py <目标文件夹路径>")
        sys.exit(1)
    start_path = sys.argv[1]
    convert_rtf_files_to_html(start_path)

方案二:自定义mammoth样式映射(保留DOCX中转)

如果必须保留DOCX中转流程,可通过mammoth的style_map参数定义文本颜色的转换规则,将DOCX中的颜色样式映射到HTML的<span>标签:

# 修改原convert_docx_to_html函数,添加style_map配置
def convert_docx_to_html(input_docx):    
    # 定义样式映射规则,捕获文本颜色
    style_map = """
    <style-name="Color" style="color:{{color}}"> <span style="color:{{color}}"></span>
    """
    with open(input_docx, "rb") as docx_file:
        result = mammoth.convert_to_html(
            docx_file, 
            convert_image=mammoth.images.img_element(convert_image),
            style_map=style_map
        )
        html = result.value
        
    output_html = os.path.splitext(input_docx)[0] + ".html"
    
    with open(output_html, "w", encoding="utf-8") as html_file:
        html_file.write(html)

    return output_html

注意:此方法依赖DOCX中的颜色样式命名规则,通用性不如方案一。

方案对比

  • 方案一:借助Word原生转换引擎,能完整保留RTF中所有格式,无需额外配置,适合大多数场景。
  • 方案二:无需依赖Word后台进程,但对DOCX样式结构有要求,仅适用于格式相对简单的文件。

内容的提问来源于stack exchange,提问作者serge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 10:37:45