KP Joy
KP Joy

Reputation: 525

FPDF PHP - Line is not working properly in second page

Following is my code which prints "HELLO", then a dotted line. This thing gets repeated 50 times. Everything is working fine but when 2nd page starts, dotted lines disappear. What modification is required in this code?

   <?php

    require("fpdf.php");

    class PDF extends FPDF
    {   
        function SetDash($black=null, $white=null)
        {
            if($black!==null)
                $s=sprintf('[%.3F %.3F] 0 d',$black*$this->k,$white*$this->k);
            else
                $s='[] 0 d';
            $this->_out($s);
        }
    }

    $pdf = new PDF('P', 'mm', 'A4');
    $pdf->AliasNbPages();
    $pdf->AddPage();
    $margin = 0;

    $pdf->SetFont('Arial','B',12);

    for ($i = 0; $i < 50; $i++)
    {
        $pdf->Cell(90, 10, "Hello", 0, 1);
        $pdf->SetDrawColor(0,0,0);
        $pdf->SetDash(2,2); 
        $margin = $margin + 10;
        $pdf->Line(10,$margin,200,$margin);
    }

    $pdf->Output();

    ?>

Upvotes: 0

Views: 720

Answers (1)

Matthias Wiehl
Matthias Wiehl

Reputation: 1998

You're incrementing the value of your $margin variable by 10 after each line even if a page break occurs in the middle of the loop. Thus, the top margin of the first line on the second page will be 10 millimeters greater than the top margin of the last line on the first page.

You need to reset the margin when a new page is added.

A solution for this problem would be to override FPDF's AcceptPageBreak method. This method intercepts the adding of a new page when the bottom of a page is reached.

class PDF extends FPDF
{
    var $lineY = 0;

    // ...

    function AcceptPageBreak()
    {
        $this->lineY = 0;
        return parent::AcceptPageBreak();
    }
}

Then, in your loop, you can do:

$pdf->Line(10, $pdf->lineY, 200, $pdf->lineY);

Upvotes: 1

Related Questions