使用mPDF+FPDI向已有PDF追加HTML/CSS时环形进度条未渲染的问题咨询
问题核心原因
- mPDF 完全不支持 Flexbox 布局:你写的
display: flex、flex-flow、justify-content等属性不会被解析,对应布局全部失效 - mPDF 默认不会将全局CSS选择器作用于SVG内部节点:全局
<style>里的类选择器无法匹配SVG内部的path、text元素,对应样式自然无法生效 - 初始化配置未开启SVG解析能力:默认参数下mPDF对SVG的解析做了安全限制,大量SVG属性会被过滤
- FPDI与Mpdf的组合使用错误:原生
Mpdf\Mpdf类没有setSourceFile、importPage、useTemplate这些方法,你当前导入现有PDF的逻辑实际未正常运行
分步修复方案
- 替换初始化类,开启SVG解析配置
直接使用FPDI适配的Mpdf子类,同时传入SVG解析相关参数,初始化代码改为:$pdf = new \setasign\Fpdi\Mpdf\Fpdi([ 'svgParse' => true, 'svgDefault' => true, 'margin_left' => 0, 'margin_right' => 0, 'margin_top' => 0, 'margin_bottom' => 0, ]); - 移除所有Flex布局代码,使用静态布局替代
删除所有和flex相关的CSS规则,外层容器用固定宽度+居中的方式实现布局,替换后的外层样式:.html-content { width: 100%; text-align: center; } .single-chart { width: 180px; margin: 0 auto; } - 取消SVG元素的类选择器,所有SVG相关样式直接内联到元素属性上
因为全局CSS不会渗透到SVG内部,直接把原来类里的样式写在SVG的对应标签上,同时不要用em这类相对单位,改用适配SVG坐标系的绝对单位,SVG代码修改为:
注意必须给SVG加固定的<div class='html-content'> <div class='single-chart'> <svg width="150" height="150" viewBox="0 0 36 36"> <path fill="none" stroke="#eee" stroke-width="3.8" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" /> <path fill="none" stroke-width="2.8" stroke-linecap="round" stroke="#ff9f00" stroke-dasharray="12, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" /> <text x="18" y="20.35" fill="#666" font-family="sans-serif" font-size="5" text-anchor="middle" >12%</text> </svg> </div> </div>width、height属性,不要用max-width、max-height这类CSS控制SVG尺寸,否则会被mPDF解析为0尺寸导致不显示。 - 调整
<style>标签内容
全局样式只保留外层HTML容器的布局规则,所有SVG相关的样式全部从全局<style>中删除,避免不必要的解析冲突。
修复后的完整代码示例
<?php use setasign\Fpdi\Mpdf\Fpdi; session_start(); ob_start(); require_once __DIR__ . '/vendor/autoload.php'; $pdf = new Fpdi([ 'svgParse' => true, 'svgDefault' => true, 'margin_left' => 0, 'margin_right' => 0, 'margin_top' => 0, 'margin_bottom' => 0, ]); $pdf->AddPage(); // 导入原有PDF页面 $pdf->setSourceFile('file.pdf'); $tplIdx = $pdf->importPage(1); $pdf->useTemplate($tplIdx, 0, 0, 297, 420, true); $html = " <style> .html-content { width: 100%; text-align: center; } .single-chart { width: 180px; margin: 0 auto; } </style> <div class='html-content'> <div class='single-chart'> <svg width="150" height="150" viewBox="0 0 36 36"> <path fill="none" stroke="#eee" stroke-width="3.8" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" /> <path fill="none" stroke-width="2.8" stroke-linecap="round" stroke="#ff9f00" stroke-dasharray="12, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" /> <text x="18" y="20.35" fill="#666" font-family="sans-serif" font-size="5" text-anchor="middle" >12%</text> </svg> </div> </div> "; $pdf->WriteHTML($html); $pdf->Output("file_new.pdf", "D"); ob_end_flush(); ?>
补充注意:如果SVG的
stroke-linecap: round仍不生效,可直接去掉该属性,或用mPDF支持的等价样式替代,mPDF对部分SVG高级属性的支持存在限制。
内容的提问来源于stack exchange,提问作者Hamdi
相关产品推荐
相关产品推荐

