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

如何在FPDF的MultiCell中手动添加换行、设置行宽或单行字符上限

解决FPDF中MultiCell文本贴右侧边缘问题

问题原因

你当前调用MultiCell()时第一个参数传值为0,FPDF中该参数代表单元格的最大宽度,传0时默认宽度会延伸到页面的右侧页边距,因此会出现文本紧贴页面右边缘的情况。

解决方法

方法1:指定单元格宽度限制(最常用)

直接修改MultiCell()的第一个参数为你需要的文本块最大宽度即可,FPDF会自动在文本达到该宽度时换行。
你当前导入的模板宽度为297mm,左侧X坐标设置为10mm,若希望右侧保留10mm边距,可将宽度设置为277(计算逻辑:297 - 10(左侧偏移) -10(右侧预留边距)),你也可以根据自己的排版需求调整数值。

修改后的代码如下:

<?php 
header('Content-Type: text/html; charset=utf-8');

require_once __DIR__ . '/vendor/autoload.php';

require_once('FPDI/autoload.php');
require_once('fpdf/fpdf.php');
require_once('FPDI/Fpdi.php'); 

$pdf = new FPDI();

$pdf->AddPage(); 

$pdf->setSourceFile('Literature.pdf'); 

$tplIdx = $pdf->importPage(1); 

$pdf->useTemplate($tplIdx, 0, 0, 297, 420, true); 

$pdf->SetTextColor(0, 0, 40);

$Text = "As they rounded a bend in the path that ran beside the river, Lara recognized the silhouette of a fig tree atop a nearby hill. The weather was hot and the days were long. The fig tree was in full leaf, but not yet bearing fruit. Soon Lara spotted other landmarks—an outcropping of limestone beside the path that had a silhouette like a man’s face, a marshy spot beside the river where the waterfowl were easily startled, a tall tree that looked like a man with his arms upraised. They were drawing near to the place where there was an island in the river. The island was a good spot to make camp. They would sleep on the island tonight.";

$pdf->SetXY(10, 50);
// 仅修改第一个参数为指定宽度即可
$pdf->Multicell(277, 8, $Text, 0, 'L', false); 

...

...
?>

方法2:按单行字符数上限换行

如果需要严格控制单行的字符数量,可先对文本进行预处理,手动插入换行符后再传入MultiCell():

  • 纯英文场景可直接用PHP内置的wordwrap()函数实现,示例:
// 限制单行最多40个字符,超出自动插入换行符
$Text = wordwrap($Text, 40, "\n", true);
$pdf->Multicell(0, 8, $Text, 0, 'L', false);
  • 包含中文等多字节字符的场景,需要使用mb_strlen()等多字节处理函数自定义断行逻辑,避免出现乱码。

注意事项

  • 宽度的单位和PDF全局设置的单位一致,默认单位为毫米
  • MultiCell()会自动识别文本中的\n作为强制换行符,你也可以手动在需要换行的位置插入\n自定义换行规则
  • MultiCell()输出完成后,当前坐标会自动移动到文本块下方的行首,无需手动调整Y坐标即可继续添加后续内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:54:02