Thursday, January 17, 2019

PHP Code to have different number of rows in first page of PDF file generated by FPDF Library


A few years back, I had published this post to explain about resolving the Wrap text issue in FPDF table cell. At the end of the post, I had specified a sample code for adding new page using addPage() on every n-th row using modulo operator.
It was working fine without any issue. But this approach won't be useful if we need different number of rows in first page of PDF than other pages. For example, in our timesheet application, the PDF report will be having some summary information at the first page of file. So, obviously the first page can hold less number of rows comparing to other pages. So, just using Modulo operator won't help in this situation. Either we need to start writing the rows from the second page, or if we want to start from first page, we have unnecessarily waste some space in all other pages.

I thought of updating the code to handle this scenario. Initially I thought it can be done very easily. After making some attempts, I realized the complexity of this scenario. I tried various approaches. But every approach is failing with any one of various test scenarios. We can imagine a lot of test scenarios.
For example,
1. Total number of rows is 0
2. Total number of rows is 1.
3. Total number of rows is less than the desired First page row count.
4. Total number of rows is exactly equal to the addition of desired first page row count and desired other pages row count or multiples of it.
5. "Greater than" instead of "Equal to" in the 4th scenario.
6. "Less than" instead of "Equal to" in the 4th scenario.

Finally I came up with below code. Based on my testing, it is working fine in all test scenarios, except when the first page row count is greater than the row count of other pages. Practically this scenario won't happen. So, I can say that it is working fine in all practical situations. Please let me know if you find any issue with this code.

$j=1;
$firstpagerowcount=14;
$otherpagesrowcount=20; //should be greater than first page count
$m=1;
foreach ((array)$data as $row)
{
$pagedata[]=$row;


if($j==$firstpagerowcount || $m==$otherpagesrowcount || $j==count($data))
{

if ($j>$firstpagerowcount)
{
$pdf->AddPage();
}
$pdf->FancyTable($header,$pagedata);

$pagedata=null;
$m=0; //start fresh

}

$m++;
$j++;
}

$pdf->Output();

No comments:

Follow By Email