2014-01-28 41 views
3

基本问题:是否可以在将MultiCell放入文档之前确定其高度?FPDF - 放置前确定MultiCell的高度?

原因:我的任务是创建PDF版本的表单。这种形式允许输入文字,并产生可变长度。一个人我什么都不输入,另一个人可以写几个段落。 “那些权力”不希望这个文本在页面之间断开。

目前,在放置每个块之后,我检查页面上的位置,如果我接近结尾,则创建一个新页面。

if($this->getY() >= 250) { 
    $this->AddPage('P'); 
} 

大多数情况下,这是有效的。但是有些少数鬼鬼祟祟的人进来了,比如249,然后有大量的文字。看起来在确定块的高度之前先确定一个块的高度是否更合理,然后才能确定它是否真正适合页面。

当然,一定有办法做到这一点,但谷歌搜索并没有证明非常有帮助。

编辑澄清:表格提交后生成PDF。不是一个活跃的,可编辑的PDF格式...

回答

4

获得此问题的风滚草徽章。 :(无论如何,在有人遇到同样问题的时候,我想我会回答我所做的事情,我怀疑这是最有效的方法,但它完成了工作。

首先,我创建了两个FPDF对象;临时的,永远不会输出,最终用户将看到的最后一个完整的pdf。

我在两个对象中得到当前的Y坐标,然后使用Cell()或MultiCell ()(对于这种形式,通常是这两种形式的组合)到临时对象中,然后检查新的Y坐标,然后我可以通过数学来确定块的高度 - 注意,数学可以得到一点时髦,如果块突破页面记住要考虑你的顶部和底部边距

现在我知道块的高度,我可以获取目标对象的当前Y坐标,从页面的总高度(减去底部边距)中减去它以获得我的可用空间。如果块合适,放置它,如果没有,添加一个页面并将其放置在顶部。

重复每个块。

我唯一需要注意的是,如果任何一个单独的单元时间长于整个页面,但是这种形式永远不会发生。 (著名的遗言......)

0

又见https://gist.github.com/johnballantyne/4089627

function GetMultiCellHeight($w, $h, $txt, $border=null, $align='J') { 
    // Calculate MultiCell with automatic or explicit line breaks height 
    // $border is un-used, but I kept it in the parameters to keep the call 
    // to this function consistent with MultiCell() 
    $cw = &$this->CurrentFont['cw']; 
    if($w==0) 
     $w = $this->w-$this->rMargin-$this->x; 
    $wmax = ($w-2*$this->cMargin)*1000/$this->FontSize; 
    $s = str_replace("\r",'',$txt); 
    $nb = strlen($s); 
    if($nb>0 && $s[$nb-1]=="\n") 
     $nb--; 
    $sep = -1; 
    $i = 0; 
    $j = 0; 
    $l = 0; 
    $ns = 0; 
    $height = 0; 
    while($i<$nb) 
    { 
     // Get next character 
     $c = $s[$i]; 
     if($c=="\n") 
     { 
      // Explicit line break 
      if($this->ws>0) 
      { 
       $this->ws = 0; 
       $this->_out('0 Tw'); 
      } 
      //Increase Height 
      $height += $h; 
      $i++; 
      $sep = -1; 
      $j = $i; 
      $l = 0; 
      $ns = 0; 
      continue; 
     } 
     if($c==' ') 
     { 
      $sep = $i; 
      $ls = $l; 
      $ns++; 
     } 
     $l += $cw[$c]; 
     if($l>$wmax) 
     { 
      // Automatic line break 
      if($sep==-1) 
      { 
       if($i==$j) 
        $i++; 
       if($this->ws>0) 
       { 
        $this->ws = 0; 
        $this->_out('0 Tw'); 
       } 
       //Increase Height 
       $height += $h; 
      } 
      else 
      { 
       if($align=='J') 
       { 
        $this->ws = ($ns>1) ? ($wmax-$ls)/1000*$this->FontSize/($ns-1) : 0; 
        $this->_out(sprintf('%.3F Tw',$this->ws*$this->k)); 
       } 
       //Increase Height 
       $height += $h; 
       $i = $sep+1; 
      } 
      $sep = -1; 
      $j = $i; 
      $l = 0; 
      $ns = 0; 
     } 
     else 
      $i++; 
    } 
    // Last chunk 
    if($this->ws>0) 
    { 
     $this->ws = 0; 
     $this->_out('0 Tw'); 
    } 
    //Increase Height 
    $height += $h; 

    return $height; 
}