2014-01-28 50 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; 
}