Tcpdf – Variable Height Table Rows With MultiCell
This post as been superseded. Please see my new post on the subject.
During my use of the excellent tcpdf library for creating pdf documents with php, I came across an interesting problem when creating a pdf featuring a grid of data. Although I could have use an html grid to present the data, I was trying to avoid the use of html and keep to the Cell(), MultiCell(), Text() etc. methods to render the document.
The content of some of the cells in this particular grid were quite long and so some wrapping of text would (and needed to) occur. The MultiCell method handles this and will wrap the text, expanding accordingly. Now I was trying to make a grid row, so needed all of the cells to be the same height – and there lay the problem – I did not know how high to make the other cells. It was a chicken and egg situation: I needed to know the height of the cell before drawing them but did not know how high they needed to be until after I had drawn them.
I studied the documentation hard but realised that the answer was not to try and generate the cells, borders and all, in one pass. I could achieve what I needed by drawing each row twice – once for the content and once for the borders.
The MultiCell function kindly returns the height that the cell was drawn, so by remembering the maximum value it was when drawing a row of cells, I could then go back and draw the borders to that maximum height:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | foreach($data as $row) { $maxnocells = 0; $cellcount = 0; //write text first $startX = $pdf->GetX(); $startY = $pdf->GetY(); //draw cells and record maximum cellcount //cell height is 6 and width is 80 $cellcount = $pdf->MultiCell(80,6,$row['cell1data'],0,'L',0,0); if ($cellcount > $maxnocells ) {$maxnocells = $cellcount;} $cellcount = $pdf->MultiCell(80,6,$row['cell2data'],0,'L',0,0); if ($cellcount > $maxnocells ) {$maxnocells = $cellcount;} $cellcount = $pdf->MultiCell(80,6,$row['cell3data'],0,'L',0,0); if ($cellcount > $maxnocells ) {$maxnocells = $cellcount;} $pdf->SetXY($startX,$startY); //now do borders and fill //cell height is 6 times the max number of cells $pdf->MultiCell(80,$maxnocells * 6,'','LR','L',0,0); $pdf->MultiCell(80,$maxnocells * 6,'','LR','L',0,0); $pdf->MultiCell(80,$maxnocells * 6,'','LR','L',0,0); $pdf->Ln(); } |
Note that the last parameter I set in MultiCell is set to 0 which means that no new line occurs once a cell is drawn. This means that the cells will appear side-by-side and also means that I need to manually create the new line when I finish drawing the row.

Recent Comments