Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the length (in pixels) of a string being rendered on a web page?

Tags:

If I know the font size (12) and the font family (calibri), is there a way to determine the length (in pixels) a given string will take after it will be rendered? I am absolutely certain about the font and size. Are there any lookup tables for this purpose to determine the length in PHP code itself? I am writing a PHP script to dynamically generate an SVG image which contains various boxes filled with data pulled out of a DB. The problem is that I need to manually wrap the text around and increase the size of the box if the string is big.

Thanks

like image 553
KJ Saxena Avatar asked Oct 29 '09 05:10

KJ Saxena


2 Answers

Use the PHP function imagettfbbox to get the size of the bounding box for the given string.

On the other hand you can use also javascript to manipulate SVG images in case you would like to handle it on the client side. That way it wouldn't even matter if the client had the specified font or not...

like image 129
kkyy Avatar answered Sep 27 '22 20:09

kkyy


You could use PHP GD to render out the string as a image and get the size of the resulting image.

If you use this, it should work:

   list($left,, $right) = imageftbbox( 12, 0, "arial.ttf", "Hello World");     $width = $right - $left; 
like image 21
jsnfwlr Avatar answered Sep 27 '22 19:09

jsnfwlr