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

使用DOMPDF生成PDF时自定义字体不生效,求解决方案及示例

自定义字体无法生效的原因及修复方案

问题原因

  1. CSS语法错误:font-weight: 900%; 中的百分号是无效语法,正确写法是 font-weight: 900;,错误语法会导致DOMPDF的渲染引擎忽略整个@font-face规则。
  2. 字体路径解析问题:CSS@font-face中直接使用服务器绝对路径,DOMPDF无法正确解析此类路径,导致无法读取字体文件。
  3. 重复注册冲突:同时通过fontMetrics->getFont和CSS@font-face注册字体,可能导致DOMPDF无法正确识别目标字体族。

修复后的示例代码

方式一:通过DOMPDF的FontMetrics注册字体(推荐)

无需在CSS中编写@font-face,直接引用注册后的字体族名即可:

<?php
require_once 'vendor/autoload.php'; // 确保引入DOMPDF自动加载文件

$dompdf = new Dompdf\Dompdf();

$fontDir = __DIR__ . '/fonts';
$customFontPath = $fontDir . '/COOPBL.ttf';

// 注册自定义字体
$fontMetrics = $dompdf->getFontMetrics();
$fontMetrics->registerFont([
    'family' => 'Cooper Black',
    'style' => 'normal',
    'weight' => 'bold',
    'path' => $customFontPath
]);

$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
    <style>
        .coop {
            font-family: 'Cooper Black';
            font-weight: bold;
        }
    </style>
</head>
<body>
    <p class="coop">这是使用Cooper Black字体的文本</p>
</body>
</html>
HTML;

$dompdf->loadHtml($html);
$dompdf->render();
$dompdf->stream('custom-font.pdf');
?>

方式二:正确配置CSS的@font-face路径

若坚持使用@font-face,需确保路径被DOMPDF正确解析,同时开启本地文件访问权限:

<?php
require_once 'vendor/autoload.php';

$dompdf = new Dompdf\Dompdf();
// 配置DOMPDF允许访问本地文件
$options = new Dompdf\Options();
$options->set('isRemoteEnabled', true);
$dompdf->setOptions($options);

// 使用相对于当前PHP文件的字体路径
$relativeFontPath = 'fonts/COOPBL.ttf';

$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
    <style>
        @font-face {
            font-family: 'Cooper Black';
            src: url('$relativeFontPath') format('truetype');
            font-weight: 900; /* 移除无效的百分号 */
            font-style: normal;
        }
        .coop {
            font-family: 'Cooper Black';
            font-weight: 900;
        }
    </style>
</head>
<body>
    <p class="coop">这是使用Cooper Black字体的文本</p>
</body>
</html>
HTML;

$dompdf->loadHtml($html);
$dompdf->render();
$dompdf->stream('custom-font.pdf');
?>

额外注意事项

  • 确保COOPBL.ttf文件存在于指定的fonts目录,且PHP进程拥有该文件的读取权限。
  • Cooper Black本身为粗体字体,需将font-weight设置为bold或900,与字体自身字重匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:47:15