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

如何使用FPDF的MultiCell方法调整PHP生成PDF表格内的数据布局

你当前代码里Row方法使用Cell绘制单元格,Cell不会自动换行,内容超出列宽时就会溢出到相邻单元格,导致布局混乱。要实现自动换行的整齐布局,需要将Cell替换为支持自动换行的MultiCell,同时统一行高,具体修改方法如下:

具体修改步骤

  1. 替换原有Row方法,同时新增计算文本行数的辅助方法,新逻辑会先计算当前行所有单元格的最大高度,再统一输出内容,保证行高一致、单元格对齐整齐:
// 替换原有Row方法
function Row($data)
{
    $this->SetX($this->TableX);
    $ci = $this->ColorIndex;
    $fill = !empty($this->RowColors[$ci]);
    if($fill)
        $this->SetFillColor($this->RowColors[$ci][0],$this->RowColors[$ci][1],$this->RowColors[$ci][2]);
    
    // 第一步:计算当前行所有单元格的最大高度
    $max_height = 0;
    $x_start = $this->GetX();
    $y_start = $this->GetY();
    
    // 先遍历一次计算每个单元格需要的高度
    foreach($this->aCols as $col) {
        $this->SetX($x_start);
        // 计算MultiCell的高度
        $nb = $this->NbLines($col['w'], $data[$col['f']]);
        $height = 5 * $nb; // 5为单元格基础行高,可根据需求调整
        if($height > $max_height) {
            $max_height = $height;
        }
        $x_start += $col['w'];
    }
    
    // 第二步:逐个输出单元格内容
    $x_start = $this->GetX();
    foreach($this->aCols as $col) {
        $this->SetXY($x_start, $y_start);
        // 输出带边框、填充、对齐的MultiCell
        $this->MultiCell($col['w'], 5, $data[$col['f']], 1, $col['a'], $fill);
        $x_start += $col['w'];
    }
    
    // 光标移动到下一行
    $this->SetXY($this->TableX, $y_start + $max_height);
    $this->ColorIndex = 1 - $ci;
}

// 新增辅助方法:计算文本需要的行数
function NbLines($w, $txt)
{
    $cw = &$this->CurrentFont['cw'];
    if($w == 0)
        $w = $this->w - $this->lMargin - $this->rMargin;
    $wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize;
    $s = str_replace("\r", '', $txt);
    $nb = strlen($s);
    if($nb > 0 && $s[$nb - 1] == "\n")
        $nb--;
    $sep = -1;
    $i = 0;
    $j = 0;
    $l = 0;
    $nl = 1;
    while($i < $nb)
    {
        $c = $s[$i];
        if($c == "\n")
        {
            $i++;
            $sep = -1;
            $j = $i;
            $l = 0;
            $nl++;
            continue;
        }
        if($c == ' ')
            $sep = $i;
        $l += $cw[$c];
        if($l > $wmax)
        {
            if($sep == -1)
            {
                if($i == $j)
                    $i++;
            }
            else
                $i = $sep + 1;
            $sep = -1;
            $j = $i;
            $l = 0;
            $nl++;
        }
        else
            $i++;
    }
    return $nl;
}
  1. 可选优化:如果content列当前设置宽度为60,若内容普遍偏长,可以适当调大该列宽度,例如修改AddCol('content',70,'Details ','C'),减少换行次数让布局更美观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:06:03