-1

I'm generating a certificate with a user name for a course platform. I want to center a text but it is not centered at all, It starts in the middle but the text is moved i. I'm using PHP 8.0 and the library MPDF. My code is the following:

$mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
$mpdf->setSourceFile('storage/' . $certificate->url); // absolute path to pdf file
$certificatePDf = $mpdf->importPage(1);

$mpdf->useTemplate($certificatePDf, 0, 0, null, null, true);
$pageSize = $mpdf->getTemplateSize($certificatePDf);
$textSize = strlen($name);
$mpdf->SetFont('Sanchez-Regular', '', 40,); 
$mpdf->SetY(130);
//centering the name on the pdf
$mpdf->WriteText($pageSize['width']/2 - $textSize/2  , 130, $name);
$mpdf->Output('newpdf.pdf');

My formula is the following: $totalPageSize/2 - $textSize/2. An example:formula result What else if left to center based on text length?

  • Use

    Text

    combination
    – Tural Rzaxanov Nov 01 '22 at 20:41
  • I am calculating by coordinates – Erick Sanabria Nov 01 '22 at 20:53
  • `$pageSize['width']` will likely be a rather large value, either in pixels or mm, I suppose? Your `$textSize` however is just the number of characters (or more precise, bytes) of your name value. `Erik Sanabria Martinez` is 22 characters, half of that is 11. – CBroe Nov 02 '22 at 07:38
  • Thank you for answering me. I read the documentation and i realized i was able to add text as a html. I just concatenated the name between a html tag. – Erick Sanabria Nov 04 '22 at 18:31

1 Answers1

0

Mpdf allows to enter text in HTML, even if you're trying to load a pdf or an HTML view as a template.

Here is what I did: My Solution

James Risner
  • 5,451
  • 11
  • 25
  • 47