使用 FPDF 限制字符串的字符数

Limit the number of characters on a string with FPDF

我正在尝试使用 FPDF 在 PDF 文档上显示一些数据,我的问题是我无法限制字符串的字符数,有时会超过宽度,我已经使用了 MultiCell 但我想设置字符限制,

我试图用我的函数自定义 echo 解决这个问题,但显然不适用于 fpdf 我不知道会发生什么。

function custom_echo($x, $length)
{
    if(strlen($x)<=$length)
    {
        echo $x;
    }
    else
    {
        $y=substr($x,0,$length) . '...';
        echo $y;
    }

}

$message= "HELLO WORLD";

$pdf=new FPDF();
$pdf->SetLeftMargin(0);
$pdf->AddPage();

$pdf->MultiCell( 95, 6, utf8_decode(custom_echo($message,5)), 0, 1);
// already tried this
$pdf->MultiCell( 95, 6, custom_echo(utf8_decode($message),5), 0, 1);

$pdf->Output();

Have you read up on the documentation? Here's an interesting example. You can create a class FPDF_CellFit and create an object of the class. See the example in this url http://www.fpdf.org/en/script/script62.php

希望对您有所帮助

PHPecho命令发送一个字符串输出。您需要 return 字符串作为函数的结果,以便 FPDF 可以使用它。

function custom_echo($x, $length) {
   if (strlen($x) <= $length) {
      return $x;
   } else {
      return substr($x,0,$length) . '...';
   }
}

可以简化为:

function custom_echo($x, $length) {
   if (strlen($x) <= $length) {
      return $x;
   }
   return substr($x,0,$length) . '...';
}

还可以做得更短,但我就是这样做的。