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

ReportLab表格中文无法正常显示的技术求助

解决ReportLab生成PDF表格中文显示异常问题

问题背景

使用Python的ReportLab库将Pandas DataFrame转换为PDF表格时,英文内容显示正常,但中文无法正常渲染。已注册Windows系统路径下的微软雅黑(msyh)字体,并设置表头使用该字体,但中文内容仍显示异常。

原代码如下:

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Table


def df_2_pdf(df, fp_pdf):
    # Create a PDF document
    pdf_filename = fp_pdf
    doc = SimpleDocTemplate(pdf_filename)

    # Load the "simhei" font
    pdfmetrics.registerFont(TTFont('msyh', r'C:\Windows\Fonts\msyh.ttc'))

    # Convert the DataFrame to a list of lists (table data)
    table_data = [df.columns] + df.values.tolist()

    # Create a Table object and set its properties
    table = Table(table_data)
    table.setStyle([
        ('TEXTCOLOR', (0, 0), (-1, 0), (0, 0, 1)),  # Header row text color
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),  # Center alignment
        ('FONTNAME', (0, 0), (-1, 0), 'msyh'),  # Use the "simhei" font for the header
        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),  # Header padding
        ('BACKGROUND', (0, 0), (-1, 0), (0.9, 0.9, 0.9))  # Header background color
    ])

    # Build the PDF document
    doc.build([table])

    print(f"PDF file '{pdf_filename}' has been created with the DataFrame.")

问题原因

原代码仅为表头行指定了支持中文的字体,但表格的数据行仍使用ReportLab默认字体(默认字体不支持中文编码),导致中文无法正常显示。此外,直接加载msyh.ttc字体集合时,若未指定字体索引,可能出现字体加载异常。

解决方法

  1. 为表格所有数据行添加中文字体配置
  2. 加载msyh.ttc时指定字体索引(微软雅黑常规体的索引为0)
  3. 可选:将字体文件打包到项目目录,避免依赖系统字体路径

修改后完整代码

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Table


def df_2_pdf(df, fp_pdf):
    pdf_filename = fp_pdf
    doc = SimpleDocTemplate(pdf_filename)

    # 加载微软雅黑字体,指定字体索引0(对应常规体)
    pdfmetrics.registerFont(TTFont('msyh', r'C:\Windows\Fonts\msyh.ttc', 0))
    # 可选:若担心系统路径问题,可将msyh.ttc复制到项目目录,使用相对路径
    # pdfmetrics.registerFont(TTFont('msyh', './msyh.ttc', 0))

    table_data = [df.columns] + df.values.tolist()
    table = Table(table_data)
    
    table.setStyle([
        # 表头样式
        ('TEXTCOLOR', (0, 0), (-1, 0), (0, 0, 1)),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('FONTNAME', (0, 0), (-1, 0), 'msyh'),
        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
        ('BACKGROUND', (0, 0), (-1, 0), (0.9, 0.9, 0.9)),
        # 数据行样式:指定字体为msyh,覆盖默认字体
        ('FONTNAME', (0, 1), (-1, -1), 'msyh'),
        ('FONTSIZE', (0, 1), (-1, -1), 10),  # 可选:设置数据行字号
        ('BOTTOMPADDING', (0, 1), (-1, -1), 8)  # 可选:设置数据行内边距
    ])

    doc.build([table])
    print(f"PDF file '{pdf_filename}' has been created with the DataFrame.")

额外说明

  • 若仍出现中文显示问题,检查字体路径是否正确,或尝试替换为其他支持中文的字体(如SimHei、KaiTi)
  • 若需要跨平台使用,建议将字体文件嵌入项目,避免依赖系统字体环境

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:16:32