Calculating string height for TCPDF library

I'm working with TCPDF to generate a PDF report, and the task looks like a nightmare. It's because TCPDF is missing some method to help you calculating the height of a string. There is a solution here , but it won't work for me. I have to spend the whole day to find out the problem and the solution seems to be very simple.

So the actual problem is getNumLines counts the lines incorrectly, I have created an issue for it. Until the author fixes the problem, you will have to use a different method to calculate the string height. Add this method to your class.

public function getStringHeight($sa,$w) {
  $sa = str_replace("\r","",$sa);
  // remove the last newline
  if (substr($sa,-1) == "\n")
    $sa = substr($sa,0,-1);
 
  $block = explode("\n",$sa);
  $wmax = $w - (2 * $this->cMargin);
 
  $lines = 0;
  $spacesize = $this->GetCharWidth(32);
 
  foreach ($blocks as $block) {
    if (!$this->empty_string($block)) {
      $words = explode(" ",$block);
 
      $cw = 0;
      for ($i = 0;$i < count($words);$i++) {
        if ($i != 0) $cw += $spacesize;
 
        $wordwidth = $this->GetStringWidth($words[$i]);
        $cw += $wordwidth;
 
        if ($cw > $wmax) { // linebreak
          $cw = $wordwidth;
          $lines++;
        }
      }
    }
 
    $lines++;
  }
 
  return $lines * ($this->FontSize * $this->cell_height_ratio);
}

Your class must be a child class of TCPDF, or you can adjust the method a little bit to suit your case. Here I just count the lines of string word by word, and check for line break when necessary. After that multiply number of lines to the fontsize to get the height of the string and then multiply to the cell height ratio to get the cell height.

I hope it will be useful for you. In my case, it saves the day :P

5 Comments

Add new comment