pdf-anti-garbled 是做什么的?
Codex 技能:在 ReportLab 生成中文 PDF 时防止乱码
问题描述
在使用 ReportLab 生成包含中文内容的 PDF 时,如果未正确配置中文字体,生成的文档中会出现乱码(例如方框或问号)。
解决方案
本技能提供以下方法防止乱码:
1. 注册中文字体
在 ReportLab 中,必须显式注册支持中文的 TrueType 字体:
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
# 注册中文字体(例如使用开源字体文泉驿微米黑)
pdfmetrics.registerFont(TTFont('WenQuanYi', '/usr/share/fonts/wenquanyi/wqy-microhei/WenQuanYiMicroHei.ttf'))
2. 在文档中使用注册的字体
在创建段落或表格时,指定该字体:
from reportlab.platypus import Paragraph
from reportlab.lib.styles import ParagraphStyle
style = ParagraphStyle(
name='ChineseStyle',
fontName='WenQuanYi',
fontSize=12,
leading=16
)
# 创建包含中文的段落
p = Paragraph('你好,世界!', style)
3. 完整示例
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
# 注册字体
pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf'))
# 创建 PDF
c = canvas.Canvas('example.pdf')
c.setFont('SimSun', 12)
c.drawString(100, 700, '中文PDF生成测试')
c.save()
注意事项
- 字体文件路径需根据实际环境调整。
- 建议使用开源字体(如文泉驿)以避免许可问题。
- 不同操作系统上的字体路径可能不同(例如 Windows 下字体在
C:\Windows\Fonts)。