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

Laravel-dompdf加载粗体font-face失败导致PDF乱码?

解决Laravel-Dompdf升级后粗体/表头乱码问题

1. 修正Font-Face定义格式

确保同时声明常规和粗体权重的字体规则,即使你的TTF文件包含粗体字重,也要明确指定权重值,同时注意路径适配Laravel9的public目录结构:

@font-face {
    font-family: 'MCS';
    src: url('../fonts/mcs.TTF') format('truetype');
    font-weight: normal;
    font-style: normal;
    font-display: swap;
}

@font-face {
    font-family: 'MCS';
    src: url('../fonts/mcs.TTF') format('truetype');
    font-weight: bold;
    font-style: normal;
    font-display: swap;
}

如果你的字体有单独的粗体文件(如mcs-bold.TTF),替换第二个规则的src路径为对应文件,能提升渲染稳定性。

2. 强制指定目标元素的字体

标签和加粗文本可能默认继承了Dompdf的内置字体,显式为这些元素指定自定义字体: ```css th, strong, [font-weight="bold"] { font-family: 'MCS', sans-serif; font-weight: bold; } ```

3. 调整Dompdf配置

先发布Dompdf配置文件(未发布过的话):

php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"

修改config/dompdf.php中的关键配置:

return [
    'font_dir' => public_path('fonts/'),
    'font_cache' => storage_path('fonts/'),
    'default_font' => 'MCS',
    'isFontSubsettingEnabled' => true,
];

确保font_dir指向正确的字体目录,font_cache目录具备写入权限。

4. 清理字体缓存

升级后遗留的旧字体缓存可能导致解析异常,执行命令删除缓存:

rm -rf storage/fonts/*

重新生成PDF时,Dompdf会自动重建字体缓存。

5. 验证PHP多字节编码配置

确认php.ini中多字节编码设置为UTF-8:

mbstring.internal_encoding = UTF-8

修改后重启PHP服务生效。

6. 优化PDF生成代码

确保生成PDF时正确加载CSS,开启HTML5解析支持:

$html = view('pdf.template')->render();
$pdf = PDF::loadHTML($html)
    ->setOptions([
        'isHtml5ParserEnabled' => true,
        'isRemoteEnabled' => true,
        'defaultMediaType' => 'screen'
    ]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 21:46:11