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

时间:2017-07-26 02:49:58

标签: php fpdf

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

我尝试用我的函数自定义回声来解决这个问题,但显然不适用于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();

2 个答案:

答案 0 :(得分:0)

  

您是否阅读了文档?这是一个有趣的例子。   您可以创建一个类 FPDF_CellFit 并创建该类的对象。   请参阅此网址http://www.fpdf.org/en/script/script62.php

中的示例

希望这有帮助

答案 1 :(得分:0)

PHP echo命令将字符串发送到输出。作为函数的结果,您需要返回字符串,以便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) . '...';
}

可以做得更短但是我会这样做。