Initial commit
This commit is contained in:
46
core/fonts.py
Normal file
46
core/fonts.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""中文字体配置。
|
||||
|
||||
reportbro-lib 的核心字体(helvetica 等)无法编码 CJK,需通过 additional_fonts
|
||||
注册支持中文的 TrueType 字体。本机使用 Windows 自带的 simhei.ttf(黑体)。
|
||||
|
||||
模板里所有样式的 font 字段必须设为这里的 value(如 "simhei")。
|
||||
若将来跨机器部署,将字体文件放入 assets/ 并改为相对路径。
|
||||
"""
|
||||
import os
|
||||
|
||||
# 模板中引用的字体名(小写,reportbro 内部按小写存储)
|
||||
CJK_FONT_NAME = "simhei"
|
||||
|
||||
# 默认字体文件路径(Windows 系统字体目录)
|
||||
_DEFAULT_FONT_PATH = r"C:/Windows/Fonts/simhei.ttf"
|
||||
_BAHNSCHRIFT_PATH = r"C:/Windows/Fonts/bahnschrift.ttf"
|
||||
|
||||
|
||||
def additional_fonts() -> list[dict]:
|
||||
"""返回 reportbro Report(additional_fonts=...) 所需的字体清单。
|
||||
|
||||
注册两类字体:
|
||||
- simhei:中文(CJK)主字体
|
||||
- bahnschrift:西文等宽风格字体,用于装箱单信息条(排产号/订单号等编号)
|
||||
若环境变量 REPORT_CJK_FONT 指定了备用 ttf 路径,则改用该路径。
|
||||
simhei 无独立 bold/italic 文件,四种字形全部映射到同一个 ttf。
|
||||
"""
|
||||
font_path = os.environ.get("REPORT_CJK_FONT", _DEFAULT_FONT_PATH)
|
||||
if not os.path.exists(font_path):
|
||||
raise FileNotFoundError(
|
||||
f"中文字体文件不存在: {font_path}\n"
|
||||
f"请安装 simhei.ttf,或通过环境变量 REPORT_CJK_FONT 指定其它支持中文的 ttf 路径。"
|
||||
)
|
||||
fonts = [
|
||||
{
|
||||
"value": CJK_FONT_NAME,
|
||||
"filename": font_path,
|
||||
# bold_filename / italic_filename / bold_italic_filename 省略,
|
||||
# reportbro 会自动把所有字形映射到 filename(见 FPDFRB 初始化)。
|
||||
}
|
||||
]
|
||||
# Bahnschrift(西文编号字体,可选;缺失不致命)
|
||||
bahn_path = os.environ.get("REPORT_LATIN_FONT", _BAHNSCHRIFT_PATH)
|
||||
if os.path.exists(bahn_path):
|
||||
fonts.append({"value": "bahnschrift", "filename": bahn_path})
|
||||
return fonts
|
||||
Reference in New Issue
Block a user