Search code examples
phppdffpdf

FPDF - How to make text to display in middle of a page?


I'm using the FPDF library to generate a PDF file.

Each page in the file is 100mm x 100mm with a 10mm margin on all sides.

The text that displays on each page varies (but should always ever be a maximum of 200 words).

I really want the text to display so it's centered perfectly in the middle of the page.

At the moment, I can get the text to be centre-aligned but am struggling to position it so it sits in the middle of the page every time. This is my code so far:

$pdf->AddPage();
$pdf->SetMargins($card_margin,$card_margin,$card_margin);
$pdf->SetAutoPageBreak(true,$card_margin);
$pdf->SetFont('Avenir','','10');
$pdf->SetAutoPageBreak(false);
    
$pdf->MultiCell(80,5,$text_to_print,0,'C');

$pdf->SetFont('Alex Brush','','13');
$pdf->MultiCell(80,10,$signee_text_to_print,0,'C');

And this is a screenshot of a PDF page that is produced from the above code:

PDF screenshot

Any ideas or suggestions would be greatly appreciated!


Solution

  • Use SetY before your call to MultiCell to "push down" where the text starts on the page. Since you indicate that it will never be more than 200 characters you should be able to estimate the height and used a fixed value for X which will get you very close to the center vertically every time.

    $pdf->SetAutoPageBreak(false);
    $pdf->SetY(100);  // for example ... value will need to be changed of course
    $pdf->MultiCell(80,5,$text_to_print,0,'C');