Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Calculate "physical" (display) width of string

I am writing PDF based on user input with the FPDF library. I am using "Arial" as my font throughout the document. Since I am putting user input into the PDF I can easily overflow the lines thus making it look ugly. For this reason I would like to know the physical width of a string at a given font size so that I can adjust the XY appropriately and\or reduce the font size and\or drop down to the next line.

For example:

 A string of 10 'W's
 WWWWWWWWWW
 is physically longer than
  a string of 10 'l's
 llllllllll

WWWWWWWWWW -vs- llllllllll

like image 908
Abtool Kabash Avatar asked Oct 25 '25 12:10

Abtool Kabash


1 Answers

Use FPDF's GetStringWidth function:

$pdf->GetStringWidth($your_string);

It returns the length of a string in user unit. A font must be selected.

like image 129
zavg Avatar answered Oct 27 '25 01:10

zavg