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

.NET Core中如何配置JSReport加载自定义字体?

在.NET Core中配置JSReport加载自定义字体的解决方案

一、确保字体文件可访问

  • 将字体文件放置在项目的wwwroot目录下,比如wwwroot/fonts/Athletics/Athletics-Regular.otf
  • 确认Program.cs中已启用静态文件中间件,否则Chrome渲染进程无法读取字体:
    app.UseStaticFiles();
    

二、修正CSS字体引用

调整@font-face的路径和格式,避免空格和路径错误:

@font-face {
    font-family: 'Athletics Regular';
    /* 使用网站根目录绝对路径,确保Chrome能正确解析 */
    src: url('/fonts/Athletics/Athletics-Regular.otf') format('opentype');
    font-weight: normal;
    font-style: normal;
}

三、配置JSReport Chrome选项

在Controller的JSReport配置中添加Chrome启动参数,强制禁用字体替换并确保兼容性:

HttpContext.JsReportFeature().Recipe(Recipe.ChromePdf)
    .DebugLogsToResponse()
    .Configure((r) =>
    {
        r.Options.Base = $"http://127.0.0.1:{HttpContext.Request.Host.Port??80}";
        r.Template.Chrome = new Chrome
        {
            MarginTop = "0mm",
            MarginLeft = "0mm",
            MarginBottom = "0mm",
            MarginRight = "0mm",
            Format = "A4",
            WaitForNetworkIddle = true,
            // 添加Chrome参数确保字体加载
            Args = new List<string>
            {
                "--disable-font-substitution",
                "--no-sandbox",
                "--disable-dev-shm-usage"
            }
        };
    });
  • --disable-font-substitution:阻止Chrome自动替换无法识别的字体
  • --no-sandbox/--disable-dev-shm-usage:解决Linux环境下的渲染兼容性问题,Windows环境也可添加

四、可选方案:嵌入Base64字体

若不想依赖静态文件路径,可将字体转换为Base64编码直接嵌入CSS:

@font-face {
    font-family: 'Athletics Regular';
    src: url(data:font/otf;base64,[字体文件的Base64编码内容]) format('opentype');
    font-weight: normal;
    font-style: normal;
}

五、验证方法

  • 在模板中添加测试文本应用自定义字体:
    <div style="font-family: 'Athletics Regular'; font-size: 24px;">自定义字体测试</div>
    
  • 通过DebugLogsToResponse()查看渲染日志,若出现字体文件404错误,需检查路径配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:05:24