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

Weasyprint生成PDF时如何正常显示繁体中文?

解决WeasyPrint生成PDF时繁体中文显示异常的问题

针对你遇到的繁体中文无法正常显示的问题,可从以下几个方向排查和修复:

1. 优先使用本地字体文件(最可靠方案)

远程字体(如Google Fonts的Noto Sans TC)可能因网络限制、WeasyPrint的远程资源加载机制等原因无法生效,建议下载字体文件到本地后引用:

  • 从Google Fonts官网下载Noto Sans TC的字体文件(选择需要的字重,比如Regular),放到项目目录下
  • 修改Python代码和CSS,显式声明本地字体:

修改后的Python代码

from weasyprint import HTML, CSS
from weasyprint.fonts import FontConfiguration

font_config = FontConfiguration()

# 内联CSS注册本地字体
local_font_css = CSS("""
@font-face {
    font-family: 'Noto Sans TC';
    src: url('NotoSansTC-Regular.otf') format('opentype');
    font-weight: normal;
    font-style: normal;
}
""", font_config=font_config)

# 加载自定义CSS
stylesheets = [local_font_css, CSS("sample.css", font_config=font_config)]

# 替换为你实际的HTML内容
html = HTML(string="<html><body>測試繁體中文:這是一段需要顯示的繁體內容</body></html>")
html.write_pdf("test.pdf", stylesheets=stylesheets, font_config=font_config)

修改后的sample.css

body {
  font-family: 'Noto Sans TC', 'Noto Sans CJK TC', 'PingFang TC', sans-serif;
  font-display: swap;
}

注:Noto Sans CJK TC是Linux/macOS常见的预装繁体中文字体,PingFang TC是macOS系统字体,确保不同环境下有可用的 fallback 字体。

2. 修复远程字体加载问题

如果坚持使用远程字体,需调整Google Fonts链接,指定字符集并确保WeasyPrint能正确解析:

  • 将CSS链接改为包含繁体子集参数,减少字体体积并确保繁体字符被包含:
stylesheets=[CSS('https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@400&subset=chinese-traditional'), CSS("sample.css", font_config=font_config)]
  • 同时确保CSS中的font-family声明和链接中的字体名称完全一致,且显式指定字重(如font-weight: 400)

3. 检查环境字体可用性

如果运行环境是Linux或macOS,微軟正黑體是Windows专属字体无法被识别,需替换为对应环境的预装繁体中文字体:

  • Linux:Noto Sans CJK TC
  • macOS:PingFang TC、Noto Sans CJK TC
  • Windows:微軟正黑體、Microsoft JhengHei

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 12:35:12