FPDF multiple columns on one page


Included is my code for displaying in pdf format data from 2 fields in 119 records. I can get the data to display in one long column spread over 3 pages. I want to display the data on 1 page over several columns. I’m stuck; don’t know how to proceed.


class PDF extends FPDF
// Page header
function Header()
// Page footer
function Footer()
// Position at 2.5 cm from bottom
    //Arial italic 8
    //Page number
    $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
$pdf = new PDF();

// Necessary for x of y page numbers to appear in document
// Document properties 
$pdf->Cell(40,10,'Class Counts');
// Add date report run
$date =  date("F j, Y");
$pdf->Cell(40,30,'Report date: '.$date);
$pdf->SetDrawColor(0, 0, 0); //black
// Table header
$pdf->SetFillColor(170, 170, 170); //gray
$pdf->setXY(10, 29.5);
// Field names
$pdf->Cell(11, 5, "CLS", 1, 0, "C", 1);
$pdf->Cell(11, 5, "CNT", 1, 0, "C", 1);
$y = 35;
$x = 10;  
$pdf->setXY($x, $y);
// Configure connection script
$query="SELECT * FROM class_counts ORDER BY `Class` ASC LIMIT 0, 500 ";

$total_count = 0;
while($row = mysql_fetch_array($result))

// Field data
  		$pdf->SetFillColor(198, 245, 175);
        $pdf->Cell(11, 5, $row['Class'], '', '','C', 1);
        $pdf->Cell(11, 5, $row['Count'], '', '','C', 1);
        $y += 5.5;
// If page break needed
        if ($y > 275)
            $y = 10;

        $pdf->setXY($x, $y);
// Total entries
$total_count += $row['Count'];

$pdf->Cell(40,15,"$total_count".' entries','','','L');



The easiest way of breaking data into columns is to retrieve all the data into an array, then use array_chunk() to produce an array of arrays of the size you want. You would then just loop over the resulting array of arrays to produce the output that you want.


I’m new to this; don’t know how to break data into arrays. Can you give specifics related to my code?


The php documentation shows how to use array_chunk - https://secure.php.net/array_chunk

You would need to calculate the number of rows per column based on the total amount of data and the number of columns. Assuming you have fetched all the data into an array named $data -

$columns = 3; // number of columns on a page
// calculate number of rows and break the data into chunks
$num_rows = ceil(count($data) / $columns);
$data = array_chunk($data,$num_rows);

You can use print_r() on the resulting $data array to see what it looks like. You would just use two nested foreach(){} loops to loop over the data to produce the columns on the page. The inner loop would produce one column and would consist of your current code that produces the single column output. After the end of the inner loop, the outer loop would set the XY position to be the start of the next column, then run the inner loop again.