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

如何在ReportLab中正确显示孟加拉语字体?PDF生成空白页问题

解决ReportLab生成孟加拉语PDF空白问题

问题原因分析

  • 样式参数拼写错误:代码中borderWidtenter code hereh是输入错误,正确参数名为borderWidth,该错误会导致ParagraphStyle初始化异常,无法正确应用样式。
  • 字体路径未正确配置:如果SutonnyMJ-Regular.ttf不在脚本当前工作目录,ReportLab无法找到字体文件,会自动 fallback 到不支持孟加拉语的默认字体,导致文本无法渲染。
  • 复杂脚本排版支持缺失:孟加拉语属于复杂书写系统,需要确保字体本身支持该语言,且注册时指定正确编码。

修正后的代码

from reportlab.pdfbase.ttfonts import TTFont 
from reportlab.pdfbase.pdfmetrics import registerFont
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.platypus import Paragraph
from reportlab.lib.styles import ParagraphStyle

# 注册孟加拉语字体,替换为字体实际路径(当前目录则保留文件名)
registerFont(TTFont('bangla', 'SutonnyMJ-Regular.ttf', encoding='UTF-8'))

# 修复样式参数错误,配置合法的样式属性
my_Style = ParagraphStyle(
    'My Para style',
    fontName='bangla',
    fontSize=16,
    borderWidth=2,
    borderPadding=(20, 20, 20, 20),  # 需传入上、右、下、左四个方向的内边距值
    leading=20,
    alignment=0
)

width, height = A4
my_path = 'hello.pdf' 
c = canvas.Canvas(my_path, pagesize=A4)

p1 = Paragraph('আমার সোনার বাংলা', my_Style)

# 调整文本容器尺寸,确保内容能完整容纳
p1.wrapOn(c, 300, 100)
# 调整绘制位置,避免超出页面可视范围
p1.drawOn(c, 100, height - 150)

c.save()

额外注意事项

  • 确认字体文件路径正确,可使用绝对路径(如'C:/fonts/SutonnyMJ-Regular.ttf'或'/usr/share/fonts/SutonnyMJ-Regular.ttf')避免路径问题。
  • 若仍无法显示,尝试更换其他支持孟加拉语的字体(如SolaimanLipi.ttf),并检查字体文件是否损坏。
  • 可添加异常捕获排查字体注册问题:
try:
    registerFont(TTFont('bangla', 'SutonnyMJ-Regular.ttf', encoding='UTF-8'))
except Exception as e:
    print(f"字体注册失败: {e}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:07:41