Laravel-Dompdf生成PDF时跨页表格rowspan失效问题求助
解决Laravel-Dompdf表格跨页后rowspan失效问题
Dompdf对跨页场景下的rowspan支持存在局限性,尤其是大跨度的rowspan(比如你代码中的rowspan="11"),可以通过以下几种方式解决:
1. 给大rowspan的表格组添加分页避免规则
给每个包含大rowspan的行组添加page-break-inside: avoid;样式,让渲染器尽量避免在这个组内分页。修改代码如下:
<style> .rowspan-group { page-break-inside: avoid; } </style> <table class="table-sm text-center align-middle"> <!-- 表头部分 --> <tr> <th rowspan="2">NAMA PASANGAN CALON</th> <th colspan="15">Rincian Perolehan Suara</th> <th rowspan="2">Jumlah <br> Tiap <br> Baris</th> <th rowspan="2">Jumlah</th> </tr> <tr> @for ($i = 1; $i <= 15; $i++) <td>{{ $i }}</td> @endfor </tr> @for ($c = 0; $c < 3; $c++) <tbody class="rowspan-group"> @for ($i = 1; $i <= 11; $i++) <tr> @if ($i === 1) <td rowspan="11">asdkjhasdkjhasdkjhasdjhsjahd and asdjaksdkasdkjkasdjh</td> @endif @for ($j = 1; $j <= 15; $j++) <td>{{ str_repeat('|', 5) }}</td> @endfor <td>{{ 5 * 15 }}</td> @if ($i === 1) <td class="align-top" rowspan="11">{{ 5 * 15 * 11 }}</td> @endif </tr> @endfor </tbody> @endfor </table>
注意:如果11行高度超过单页剩余空间,该规则可能不生效,此时需要手动拆分表格。
2. 手动拆分表格并重复表头
当行组必然跨页时,把每个大rowspan的行组拆分为独立表格,在新页重复表头,确保rowspan在单页内完整:
@for ($c = 0; $c < 3; $c++) <table class="table-sm text-center align-middle"> <tr> <th rowspan="2">NAMA PASANGAN CALON</th> <th colspan="15">Rincian Perolehan Suara</th> <th rowspan="2">Jumlah <br> Tiap <br> Baris</th> <th rowspan="2">Jumlah</th> </tr> <tr> @for ($i = 1; $i <= 15; $i++) <td>{{ $i }}</td> @endfor </tr> @for ($i = 1; $i <= 11; $i++) <tr> @if ($i === 1) <td rowspan="11">asdkjhasdkjhasdkjhasdjhsjahd and asdjaksdkasdkjkasdjh</td> @endif @for ($j = 1; $j <= 15; $j++) <td>{{ str_repeat('|', 5) }}</td> @endfor <td>{{ 5 * 15 }}</td> @if ($i === 1) <td class="align-top" rowspan="11">{{ 5 * 15 * 11 }}</td> @endif </tr> @endfor </table> <div style="page-break-after: always;"></div> @endfor
3. 升级Dompdf版本
部分旧版本Dompdf存在跨页rowspan渲染bug,建议升级到最新稳定版,执行Composer命令:
composer require dompdf/dompdf:^2.0
新版本对表格跨页的渲染逻辑有优化。
4. 用嵌套表格模拟rowspan
如果上述方法无效,可将原表格拆分为并排的嵌套表格,通过边框对齐模拟rowspan效果:
<div style="display: flex; border-collapse: collapse;"> <!-- 左侧rowspan列 --> <table class="table-sm text-center align-middle"> <tr><th rowspan="13">NAMA PASANGAN CALON</th></tr> @for ($i = 1; $i <= 11; $i++) <tr><td></td></tr> @endfor </table> <!-- 中间内容列 --> <table class="table-sm text-center align-middle"> <tr><th colspan="15">Rincian Perolehan Suara</th><th>Jumlah <br> Tiap <br> Baris</th></tr> <tr> @for ($i = 1; $i <= 15; $i++) <td>{{ $i }}</td> @endfor <td></td> </tr> @for ($i = 1; $i <= 11; $i++) <tr> @for ($j = 1; $j <= 15; $j++) <td>{{ str_repeat('|', 5) }}</td> @endfor <td>{{ 5 * 15 }}</td> </tr> @endfor </table> <!-- 右侧rowspan列 --> <table class="table-sm text-center align-middle"> <tr><th rowspan="13">Jumlah</th></tr> <tr><td></td></tr> @for ($i = 1; $i <= 11; $i++) <tr> @if ($i === 1) <td rowspan="11" class="align-top">{{ 5 * 15 * 11 }}</td> @endif </tr> @endfor </table> </div>
需额外调整CSS保证边框和对齐一致,但能避免跨页rowspan问题。
内容的提问来源于stack exchange,提问作者SAT YA
相关产品推荐
相关产品推荐

