使用DOMPDF生成PDF时自定义字体不生效,求解决方案及示例
自定义字体无法生效的原因及修复方案
问题原因
- CSS语法错误:
font-weight: 900%;中的百分号是无效语法,正确写法是font-weight: 900;,错误语法会导致DOMPDF的渲染引擎忽略整个@font-face规则。 - 字体路径解析问题:CSS@font-face中直接使用服务器绝对路径,DOMPDF无法正确解析此类路径,导致无法读取字体文件。
- 重复注册冲突:同时通过
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
相关产品推荐
相关产品推荐

