Search code examples
phpfpdf

FPDF: Footer of first page gets printed with data of second page


I am using FPDF to generate 3 page pdf. Have extended FPDF class to add header, footer and a function for main content.

enter image description here

Then I use array which contains 3 header and footer names which I display on every page just to demonstrate the issue I am facing.

enter image description here

Once the first page is loaded, variable $i is 0 and the first header name, i.e "Header 1" gets printed. Main Content also gets printed but "Footer 1" does not print just yet.

Value of $i increments to 1, now the value in $footerName is "Footer 2" and now it gets printed on the first page. "Footer 3" gets printed on second page. This is the issue I am facing, header and everything else is working fine but footer isn't.

It is not waiting for footer to finish but instead running the next set of code and starting the next page processing and then it prints footer of previous page with incorrect data.

enter image description here


Solution

  • You should write your loop in this order :

    for ($i = 0 ; $i < 3 ; $i++) {
        $headerName = $headerNames[$i];
        $pdf->AddPage();
        $footerName = $footerNames[$i];
        $pdf->mainContent();
    }
    

    Because page1's Footer() function is called at the second addPage(), page2's Footer is called at the third addPage(), ...