Community研究与数据分析github.com

bluegum8013-creator/pdf-anti-garbled

Codex 技能:在 ReportLab 生成中文 PDF 时防止乱码

pdf-anti-garbled 是什么?

该 AI 技能专为解决在使用 ReportLab 库生成中文 PDF 时出现的乱码问题而设计。它提供了一组配置和代码示例,帮助开发者正确设置中文字体,确保在生成的 PDF 文档中汉字能够正确显示。该技能适用于任何使用 ReportLab 进行 PDF 生成的 Python 项目,通过引入合适的中文字体文件(如 SimSun、SimHei 等)并正确配置字体对象,可以有效避免因字体缺失或设置不当导致的乱码现象。技能中包含的 SKILL.md 文档详细说明了如何在代码中注册中文字体、设置文本编码以及处理不同操作系统下的字体路径问题。

兼容平台~Claude Code✓Codex CLI~Cursor
npx skills add bluegum8013-creator/pdf-anti-garbled

Installed? Explore more 研究与数据分析 skills: affaan-m/uspto-database, affaan-m/scholar-evaluation, affaan-m/literature-review · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

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)。

相关资源

相关技能