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

如何确保跨多页的TCPDF表格行高完全一致?

解决TCPDF表格跨页时行高不一致的问题

方案1:用单元格固定高度替代line-height

TCPDF对CSS line-height的分页处理稳定性不足,直接给<td>设置固定height属性,并搭配vertical-align确保内容垂直居中,可强制所有行保持统一高度。

修改后的表格生成代码:

$cells = '';
$n = 0;
while ($n < 100) {
    if (++$n % 2 == 1) {
        // 给单元格添加固定高度与垂直对齐样式
        $cells .= "<tr><td style=\"height:3cm; vertical-align:middle;\">Cell $n</td>";
    } else {
        $cells .= "<td style=\"height:3cm; vertical-align:middle;\">Cell $n</td></tr>";
    }
}
$pdf->writeHTML("<table border=\"1\">$cells</table>", true, false, true, false, '');

方案2:手动分页控制(彻底解决截断问题)

如果方案1仍有异常,可禁用自动分页,手动计算每页可容纳的行数,将表格拆分为多个子表格分页面输出,从根源避免分页截断行导致的高度错乱:

完整修改代码:

require_once('TCPDF-master/tcpdf.php');
class MYPDF extends TCPDF {
    public function Header() {}
    public function Footer() {}
}
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->AddPage();
$pdf->SetMargins(10, 10, true);
// 禁用自动分页,改为手动控制
$pdf->SetAutoPageBreak(false, 10);

// 计算每页可容纳行数:页面可用高度 ÷ 行高(默认单位为mm,3cm=30mm)
$pageAvailableHeight = $pdf->getPageHeight() - $pdf->getMargins()['top'] - $pdf->getMargins()['bottom'];
$rowHeight = 30;
$rowsPerPage = floor($pageAvailableHeight / $rowHeight);

$totalRows = 50; // 循环生成50行(对应100个单元格)
$currentRow = 0;

while ($currentRow < $totalRows) {
    $cells = '';
    // 生成当前页的表格行
    for ($i = 0; $i < $rowsPerPage && $currentRow < $totalRows; $i++) {
        $currentRow++;
        $cell1Num = ($currentRow * 2) - 1;
        $cell2Num = $currentRow * 2;
        $cells .= "<tr>
            <td style=\"height:3cm; vertical-align:middle;\">Cell $cell1Num</td>
            <td style=\"height:3cm; vertical-align:middle;\">Cell $cell2Num</td>
        </tr>";
    }
    // 输出当前页表格
    $pdf->writeHTML("<table border=\"1\">$cells</table>", true, false, true, false, '');
    // 剩余行未输出则新增页面
    if ($currentRow < $totalRows) {
        $pdf->AddPage();
    }
}

$pdf->Output('Test.pdf','F');

补充提示

  • 尽量避免依赖CSS line-height控制行高,TCPDF对CSS的支持有限,直接设置单元格height的兼容性更强。
  • 手动分页时注意单位转换(默认PDF_UNIT为mm,1cm=10mm),确保行高计算准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 03:15:54