Search code examples
phppdfpdf-generationfpdffpdi

Experiencing weird top margin when using fpdf Write()


I'm trying to write text to a PDF and there seems to be a weird margin on the top of my page.

This is my following code:

require_once('fpdf.php');
require_once('fpdi/fpdi.php');

//Start the FPDI
$pdf = new FPDI('P', 'pt');

//Set the source PDF file
$source_file = $pdf->setSourceFile("template.pdf");

//Import the first page of the file
$tppl = $pdf->importPage(1);

$pdf->AddPage();

//get size of pdf page
$size = $pdf->getTemplateSize($tppl);

$pdf->useTemplate($tppl, null, null, $size['w'], $size['h'], true);
$pdf->SetMargins(0, 0, 0);
$pdf->SetTextColor(0, 0, 0); 

When I use a font-size pt 12, and write text I get this:

$pdf->SetFont('Arial', '', 12);
$pdf->SetXY(0, 0);
$pdf->Write(0, "Hi");

enter image description here

When I do $pdf->SetXY(0, 7.5) I get this

enter image description here

The above looks like I can easily add 7.5 points to the Y and be fine.

However, if I changed the font-size, the distance between the top and the text grows a little greater.

$pdf->SetFont('Arial', '', 8);

enter image description here

Could anyone help me figure out how to neutralize this to at least make it so if I set my XY to a number, it will put it on the some location regardless of the font-size? I've tried different pdf's and it works all the same.

EDIT:

I did $pdf->GetY() and I get 28.35


Solution

  • I solved this by instead of doing Write() I used Cell().

    I think the main issue was not having a solid width and height. All I know is it works perfectly now so anyone encountering the same problems should try this.

    $pdf->Cell(WIDTH,HEIGHT,TEXT);
    

    I also did the following, not sure if this helped or not but I have it in my script.

    $pdf->SetMargins(0, 0);
    $pdf->cMargin = 0;