Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a datafeed that needs to truncate certain lines so that they don't break across lines in a specific width table in HTML output (web designers can be particular). In other words, I need to be able to figure out how many pixels wide a particular text string will be when rendered in a given truetype font at a given font size.

Other than dumping the font metrics to a table (the designers are using a single Web-ish true-type font in 11pts), how can I determine the string width, accounting for paired kerning?

I have looked at various modules from CPAN for getting TTF metrics, but have yet to find an example of what I suspect is a common problem, e.g., determining the rendered width of the string.

Can anyone provide any pointer to where I might look for example code in Perl, C, or Java?

  • Comment on Length of rendered TTF string in pixels?

Replies are listed 'Best First'.
Re: Length of rendered TTF string in pixels?
by steveAZ98 (Monk) on Jul 24, 2000 at 05:45 UTC
    If you can use images for the creation of the text, then maybe you could use Image::Magick to draw the text and also find the dimensions of the text.
    $image->Read('How long am I'); ($text_width) = $image->Get('width');
    I found this information in "Programming Web Graphics" by Shawn P. Wallace (pg. 141) This is the only way I know of to find the pixel width of an object on a webpage.
    Here is a quick script so you can try it out and see if it's what your looking for.
    HTH
    use Image::Magick; my $image = Image::Magick->new(); my $ps = 15; $image->Set(pointsize=>$ps); $image->Read("Label: Test "); my $l = $image->Get('width'); print $l, "\n";
Re: Length of rendered TTF string in pixels?
by lhoward (Vicar) on Jul 24, 2000 at 07:48 UTC
    repeat after me :

    HTML is not a typesetting protocol. Anything you do short of creating your entire page as a raster graphic or other absolute format (such as Acrobat) will be rendered and displayed differently depending on how the client is viewing the information (browser, screen size, etc). Even if you use Cascading Style Sheets defining the precise pixel-by-pixel rendering of a page is impossible.

      Preacher, turn around! You're facing the choir. <beg>
      Unfortunately, the page-layout turned web people don't view things that way.
      A requirement is a requirement, no matter how small.
      the original AMonk
RE: Length of rendered TTF string in pixels?
by Russ (Deacon) on Jul 24, 2000 at 06:42 UTC
Re: Length of rendered TTF string in pixels?
by Anonymous Monk on Jul 25, 2000 at 01:56 UTC