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

如何在FPDF的MultiCell中实现多行不同文本属性及换行修复

问题解答

1. 实现两行文本不同样式的文本框

完全可以实现,但无法通过一次MultiCell完成——因为MultiCell会把当前设置的字体样式应用到所有内容上。推荐两种可行方案:

方案一:先绘边框再逐行写入文本

先画出完整的矩形边框,再在框内分别设置不同字体样式写入两行,通过GetX()和GetY()精准控制位置:

public function print()
{
    $this->fpdf->AddPage('L',[100,150]);
    
    $x = $this->fpdf->GetX();
    $y = $this->fpdf->GetY();
    $cellWidth = 130;
    $lineHeight = 8;
    
    // 绘制矩形边框
    $this->fpdf->Rect($x, $y, $cellWidth, $lineHeight * 2);
    
    // 第一行:Arial粗体16号
    $this->fpdf->SetFont('Arial','B',16);
    $this->fpdf->MultiCell($cellWidth, $lineHeight, utf8_decode('Material description :'), 0);
    
    // 回到第二行起始X坐标,设置新字体
    $this->fpdf->SetX($x);
    $this->fpdf->SetFont('Arial','',12); // 示例改为常规12号字体
    $this->fpdf->MultiCell($cellWidth, $lineHeight, utf8_decode('V-001940 LCMS AA001'), 0);
    
    $this->fpdf->Output();
}

方案二:拆分MultiCell拼接边框

通过设置MultiCell的边框参数,让两行的边框拼接成完整的文本框:

public function print()
{
    $this->fpdf->AddPage('L',[100,150]);
    
    $cellWidth = 130;
    $lineHeight = 8;
    
    // 第一行:上、左、右边框,粗体16号
    $this->fpdf->SetFont('Arial','B',16);
    $this->fpdf->MultiCell($cellWidth, $lineHeight, utf8_decode('Material description :'), 'LTR');
    
    // 第二行:左、右、下边框,常规字体
    $this->fpdf->SetFont('Arial','',12);
    $this->fpdf->MultiCell($cellWidth, $lineHeight, utf8_decode('V-001940 LCMS AA001'), 'LRB');
    
    $this->fpdf->Output();
}

2. 解决\n换行无效的问题

FPDF只识别ASCII换行符(即chr(10),LF),\n无效通常是字符串引号类型导致的:

  • 若使用单引号字符串,\n会被当作字面量字符,不会解析为换行;此时要么继续用chr(10),要么换成双引号字符串。
  • 若使用双引号字符串,\n会自动解析为LF换行符,就能正常生效。

修改示例:

// 双引号字符串中,\n可正常换行
$this->fpdf->MultiCell(130,8,utf8_decode("Material description :\nV-001940 LCMS AA001"),1);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:01:05