Positioning text over pdf file in PHP

8.3k Views Asked by At

I'm developing an e-Certificate web page. I've managed loading the certificate template and writing on top of it (Attendee Name, Event Title and Event Date). But in positioning those three pieces of information, I couldn't position them at the center no matter how long they are. they always start from x point.

Check my work result:

enter image description here

Code:

<?php
require_once('fpdf.php');
require_once('fpdi.php');

$pdf =& new FPDI();
$pdf->addPage('L');
$pagecount = $pdf->setSourceFile('Certificate.pdf');
$tplIdx = $pdf->importPage(1); 
$pdf->useTemplate($tplIdx); 
$pdf->SetFont('Times','I',18);
$pdf->SetTextColor(0,0,0); 
$pdf->SetXY(120, 62); 
$pdf->Write(0, "Attendee Name"); 

$pdf->SetXY(120, 102); 
$pdf->Write(0, "Event Name"); 

$pdf->SetXY(120, 140); 
$pdf->Write(0, "Event Date"); 
$pdf->Output();
?>

Is there away to center the text no matter how long is it?

meaning without fixing the x point. however, the y point result is very good.

2

There are 2 best solutions below

0
On BEST ANSWER

So 2 ways I've done this before, the most likely easiest way: Since you only have 1 entry on the row (Attendee Name or Event Name, etc) Start a cell at the left most point, and have the cell run the full width of the page, then specify the center option:

$pdf->SetXY(0,62);
//0 extends full width, $height needs to be set to cell height.
$pdf->Cell(0, $height, "Attendee Name", 0, 0, 'C');

The other option is to calculate the center, and set X accordingly:

//how wide is the page?
$midPtX = $pdf->GetPageWidth() / 2;
//now we need to know how long the write string is
$attendeeNameWidth = $pdf->GetStringWidth($attendeeName);
//now we need to divide that by two to calculate the shift
$shiftLeft = $attendeeNameWidth / 2;
//now calculate our new X value
$x = $midPtX - $shiftLeft;
//now apply your shift for the answer
$pdf->setXY($x, 62); 
$pdf->Write(0, "Attendee Name"); 

You can then repeat the above for each of the other elements.

0
On

You need a way to calculate the string length in pixels of the string (say, 120 pixels) and you need to know the page width in pixels.

At that point you position the string at x = (pagewidth/2 - stringwidth/2) and Bob's your uncle.

In FPDI you do this with GetStringWidth and GetPageWidth.

You can do the same adjustment with the height. For example you can split the string in words, calculate the width of each one, and determine when it is too much. This way you can split the string in two, and center each section.