Search code examples
phpfpdf

FPDF right margin values have no effect


I am using the PHP extension FPDF to create PDF documents. I believe I have the margins set to 1" all the way around with justified text, but when I create a PDF document, download it and open it in Acrobat, I see the left margin is 1" but the right margin is about 1.2". I've gone through fpdf.php looking for the issue and cannot find it.

$oPdf = new myPDF('P', 'mm', 'letter');

$oPdf->Open();
$oPdf->SetMargins(25.4,25.4,25.4,25.4);

//set default font/colors
$oPdf->SetFont('Times', '', 12);
$oPdf->SetTextColor(0,0,0);
$oPdf->SetFillColor(255, 255, 255);

//add the page
$oPdf->AddPage();
$oPdf->AliasNbPages();

If I change the top and left margin values, the document reflects the changes. If I change the bottom or right, there is no change. I've seen how the bottom can be changed wth set auto default page break, answered elsewhere. My question is how can I change the right margin and it actually take effect in my document? I have a feeling that this has to do with the measurement of the text when FPDF calculates whether the justified text will fit on the line. I've checked the width of the line and it outputs 165.1 (which is 6.5 inches x 25.4mm) Completely stumped.


Solution

  • Ok, I feel kind of dumb, but hopefully this will help others. I use the FpdfMulticell (See http://www.interpid.eu/fpdf-multicell) for more control over cells and other parts of displaying the content on the PDF document. This is great and all, except for the redundancies that are created. The components of this function require width and height for the cell to be created. This is where the problem was. For some reason I was passing 160 to it rather than 165.1. 6.5" x 25.4 = 165.1. When I go through the references to create the multiCell function within the class, it fixes my problem.

    If you're going to use the multicell, I suggest declaring a variable at the beginning of your page such as $pw (i.e., page width) and then instead of passing a constant value, pass the variable. That way your values are uniform and if you want to change it up, then you only have 1 value to change. Make sure you comment so you know what the purpose of that variable is.

    $oMulticell = new FpdfMulticell($oPdf);
    $pw = 165.1
    //Make sure that the content is long enough to go to another line or you won't
    //notice the difference with the justified text
    $content = "Write some text here Write some text here Write some text here Write some text here Write some text here Write some text here Write some text here Write some text here ";
    $oMulticell->multiCell($pw,10,$content,0,"J",1,0,0,0,0);
    

    This works!