TCPDF: Paging those MultiCells

Here’s something that I ran into:

Let’s say you need to write out some tables to a PDF that you are dynamically building.  You grab the multicell command, everything looks good, and then you get an automatic page break.  Suddenly, your PDF looks like puke on a plate: the cells overwrite each other, rows are on top of rows, rows stretch awkwardly across the page break.

Here’s a way to make MultiCell page breaks look good.  I tried this in TCPDF 5 — the use of the current page function was not working for me.  (You’re not writing in iTextSharp anymore!)

protected function writeMulticells($cell_array) {
    $this->pdf->setAutoPageBreak(false);
    $this->pdf->startTransaction();
    foreach ($cell_array as $row) {
        $this->pdf->MultiCell($row[0], $row[1],
                                    $row[2], $row[3],
                                    $row[4], $row[5],
                                    $row[6]);
    }
    $this->pdf->ln(); 

    if ($this->pdf->getY() > $this->pdf->getPageHeight() - 30) {
        $this->pdf->rollbackTransaction(true);
        $this->pdf->AddPage();
        foreach ($cell_array as $row) {
            $this->pdf->MultiCell($row[0], $row[1], $row[2],
               $row[3], $row[4], $row[5], $row[6]);
        }
        $this->pdf->ln();
    }
    $this->pdf->commitTransaction();
    $this->pdf->setAutoPageBreak(true, 30);
}

(I just happened to have this inside a CodeIgniter model, hence the protected function.)

What we do is the following:

  1. Disable auto page breaks.
  2. Start a transaction.
  3. Write the row.
  4. If you would have crossed into the footer, roll back, make a new page, and write the row again.
  5. Commit the transaction.
  6. Re-enable auto page breaks.

All of the examples I could find suggested using the getPage function, but that didn’t work all of the time in my particular application. Your mileage may vary, of course, but here’s an alternative option.

Comments are closed.