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

使用fpdf2从HTML生成PDF时文字颜色不显示的问题排查

问题原因及解决方案

原因

fpdf2的HTMLMixin对HTML内联样式的支持范围有限,不识别<p>标签style属性中的color设置。该组件的HTML解析逻辑仅针对特定标签(如<font>)的color属性做了处理,不会解析通用style属性里的样式规则,所以你设置的颜色会被直接忽略,PDF文字保持默认黑色。

修复方案

方案1:改用<font>标签设置颜色

HTMLMixin原生支持<font>标签的color属性,修改create_html函数即可:

def create_html(text, hex_codes):
    result = nltk.sent_tokenize(text)
    hex1 = hex_codes[0]
    hex2  = hex_codes[1]
    flag = True
    res = []
    for sentence in result:
        if flag:
            hex = hex1
        else:
            hex = hex2
        flag = not flag
        # 用<font>标签替代p的style设置颜色
        res.append(f"<p><font color='{hex}'>{sentence}</font></p>")
    return ''.join(res)

方案2:绕过HTML解析,用fpdf2原生API设置颜色

直接通过fpdf2的原生方法逐句配置颜色并写入,避免HTML解析的限制:

def create_pdf(text, hex_codes):
    pdf = PDF()
    pdf.add_page()
    sentences = nltk.sent_tokenize(text)
    hex1, hex2 = hex_codes
    flag = True
    for sentence in sentences:
        # 将十六进制颜色转为RGB值(fpdf2需要RGB整数参数)
        current_hex = hex1 if flag else hex2
        r = int(current_hex[1:3], 16)
        g = int(current_hex[3:5], 16)
        b = int(current_hex[5:7], 16)
        # 设置文字颜色
        pdf.set_text_color(r, g, b)
        # 写入句子,8为行高,可按需调整
        pdf.write(8, sentence + "\n\n")
        flag = not flag
    return BytesIO(pdf.output())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 14:54:15