【问题标题】:Division by zero on Cellfit using FPDF使用 FPDF 在 Cellfit 上除以零
【发布时间】:2019-01-20 12:24:34
【问题描述】:

我正在使用 fpdf 生成关于 pdf 文件的报告,我正在尝试使用 CellFit 函数将文本放入单元格中,但错误显示 > 第 49 行除以零。请帮助我。谢谢你。这是我的代码:

//Cell with horizontal scaling if text is too wide
function CellFit($w, $h=0, $txt='', $border=0, $ln=0, $align='', 
$fill=false, $link='', $scale=false, $force=true)
{
    //Get string width
    $str_width=$this->GetStringWidth($txt);

    //Calculate ratio to fit cell
    if($w==0)
        $w = $this->w-$this->rMargin-$this->x;
        $ratio = ($w-$this->cMargin*2)/$str_width; //This is line 49


    $fit = ($ratio < 1 || ($ratio > 1 && $force));
    if ($fit)
    {
        if ($scale)
        {
            //Calculate horizontal scaling
            $horiz_scale=$ratio*100.0;
            //Set horizontal scaling
            $this->_out(sprintf('BT %.2F Tz ET',$horiz_scale));
        }
        else
        {
            //Calculate character spacing in points
            $char_space=($w-$this->cMargin*2-$str_width)/max($this->MBGetStringLength($txt)-1,1)*$this->k;
            //Set character spacing
            $this->_out(sprintf('BT %.2F Tc ET',$char_space));
        }
        //Override user alignment (since text will fill up cell)
        $align='';
    }

    //Pass on to Cell method
    $this->Cell($w,$h,$txt,$border,$ln,$align,$fill,$link);

    //Reset character spacing/horizontal scaling
    if ($fit)
        $this->_out('BT '.($scale ? '100 Tz' : '0 Tc').' ET');
}

【问题讨论】:

  • 确保您的值大于 0。除以零是不可能的。您可以发布 $str_width 的内容吗?
  • 可能不相关,但从您的缩进来看,我怀疑您想为if($w==0)两件事——在这种情况下,您必须将这两件事放在{} 之间。没有它们,只有第一个命令符合条件,第二个命令无论如何都会执行。
  • @rickdenhaan 非常感谢您的解释。现在,我明白错误的含义了。 $str_width 的值不能为空或零。
  • 没错。该功能旨在使文本适合单元格。如果您没有任何文本可放入单元格中(即 $txt 为 null 或空字符串),请不要使用该函数(或修改它以能够处理这种情况)。
  • @YvetteLee 您可以尝试类似if (empty($txt)) return; 作为该函数中的第一件事(在$str_width 定义之前)。

标签: php fpdf


【解决方案1】:

我添加了这个并为我解决了这个问题。我的值是 NULL。

//Cell with horizontal scaling if text is too wide
function CellFit($w, $h=0, $txt='', $border=0, $ln=0, $align='', 
$fill=false, $link='', $scale=false, $force=true)
{

//Add this line here, Convert NULL to '---'. 
if (empty($txt)) 
{
    $txt='---';
}

     //Get string width
     $str_width=$this->GetStringWidth($txt);

【讨论】:

  • if ($txt==NULL) 应该是 if(is_null($txt)) 以获得更好的编码一致性
  • ($txt='---');不应有括号:$txt = '---';
  • 另外,为了保持一致性,您可能应该使用 if (empty($txt)) 。这也将适合函数给定的$txt 的默认值。
猜你喜欢
  • 2014-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
  • 1970-01-01
相关资源
最近更新 更多