Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Pixel length of strings

by TruthSeeker (Initiate)
on Jul 11, 2009 at 18:07 UTC ( #779235=perlquestion: print w/replies, xml ) Need Help??

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

I am writing a Perl program that generates HTML that needs to be explicitly formatted (it is a playoff bracket). In order to generate the right number of characters, I can either used a fixed-width font (e.g. Courier New) which I much prefer not to do, or have some way of counting the pixel length of characters and/or strings. I researched this a few months back and thought I had found an appropriate library call that supported this, but I evidently didn't save the link and can't seem to find it again. Any help in finding a perl function that will return the pixel length given a font, font size and string would be much appreciated.

Replies are listed 'Best First'.
Re: Pixel length of strings
by Your Mother (Archbishop) on Jul 11, 2009 at 20:37 UTC

    You have a few options I think. You can do it as a graphic with Image::Magick, Imager (not sure about this one), or GD; at least a couple of those support some font metrics stuff but I haven't used it (and I'm a former typographer) because it's very low level and not fun. You can use tables and they will line up correctly. You can use CSS which either uses the table style rules, uses overflow rules, or is dynamically written in ex widths and presented in a mono-space font. You could even use LaTeX and present a PDF or a gif/png of a generated PDF. Update: SVG could work too... but I think a text heavy page in it would end up being *huge*. And you'd still be stuck with generating it in a defined/fluid grid.

    Of those I'd argue that the font based stuff is probably the last and most difficult option.

Re: Pixel length of strings
by ww (Archbishop) on Jul 11, 2009 at 21:47 UTC
    Sorry, I'd be with those who suggest SVG, .jpg, .pdf and similar...
    if I really believed that your rendering "needs to be explicitly formatted (it is a playoff bracket)..."

    But I don't. This is not an application that requires the precision of a blueprint or mechanical drawing.

    Given the issues with fonts, user settings, cross-browser variance (to name just a few), I'd be very surprised if you need more than thoughtful CSS (width: nn units; max-width: nn units) or well spec'ed tables (widths -- as units of whatever flavor floats your boat -- for the table and the individual TDs). Either approach should get you close enough to work for 99% of your users. IMO, you'ld be well advised to assume a screen width of NMT 800 pixels and a rendering area which allows for chrome.

    At that point, you can work out roughly how many chars fit a given column(s if you're sneaky with column-spans) and turn your problem on it's head: "In order to generate the right number of characters, calculate/experiment with something like a fairly wide 12 point font size, and instead of calculating widths, decide how to truncate/abbreviate your listings.

      I'm with you, now that I googled what a "playoff bracket" is. It's at least a matter of font-width, nested tables or divs with overflow-styles should be more than sufficient.

      Cheers Rolf

Re: Pixel length of strings
by mzedeler (Pilgrim) on Jul 11, 2009 at 18:25 UTC

    I wouldn't use HTML in the first place. Why not use SVG?

      I don't know what SVG is. My perl programs generate HTML which is then (after a little massaging) published as a web page. This is all part of a softball website that I support.

        I believe the point the monk above was making is that "HTML IS NOT PIXEL PERFECT".

        You're at the whim of the fonts the end user has chosen, their preferred display size, differences in rendering, and more.

        If you absolutely must have something be pixel perfect use an image, PDF, or similar.


        Scalable Vector Graphics (SVG) is a standard for including vector graphics (drawings) into a HTML page.

        HTML itself does not (and can not) guarantee how your page is rendered, for it is a device independent format. You can't be sure even that your page is rendered as text (braille browsers, voice synthesis, etc.)

        So pure HTML is not the right choice for a fixed format output; on the other hand, SVG is a format for specifying graphics and compliant browsers (most if not all modern browsers) try to render it exactly as you specified.

        Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."

        Trying to emulate the layout descisions made by the browser (note that there are many browser distributions and versions each doing it slightly differently) is neither anticipated by the browser developers nor a generally good design, since HTML never was supposed to give complete control of the final layout.

        SVG is very easy to generate and you have much more accurate control of the layout. If you have to deal with browsers that doesn't understand it, you can use a server side tool to render a bitmap image from SVG.

        Since it is an XML based standard, it is straight forward to create templates and use them much the same way you'd publish web pages. All you need to change is the content type.

        Try taking a look at some SVG examples or the SVG specification.

        Another obvious alternative to SVG is generating bitmap graphics straight away as suggested in other posts.

Re: Pixel length of strings
by ruzam (Curate) on Jul 12, 2009 at 00:18 UTC
    Isn't this a page layout problem? What would you do with the pixel length of the characters that you wouldn't do with a properly designed flowing page in the first place? The user's browser is going to mess with your font character lengths more ways than a swamp has bugs regardless of what method you use to determine the string length and you have absolutely no control over that.
Re: Pixel length of strings (Javascript+DOM)
by LanX (Cardinal) on Jul 11, 2009 at 21:18 UTC
    let's assume you can use a font which renders exactly the same in all browsers and is per default installed on all OSes...

    You can use Javascript to determine the pixel length of this font!

    E.g. by reading the coordinates of embracing links, this already worked with Netscape4-"DOM" and I used it this way to get font-width.

    So just send a HTML-Page to your browser with the font and the JS and read out the results.

    You can do it via a webserver and a form-submit (or AJAX's XmlHttpRequest) with the results or even by remotely telling a local Firefox to load and save the (enriched) local webpage (-remote option)

    Cheers Rolf

    UPDATE: Should even be possible to send the JS-Code via telnet to a MozRepl AddOn in FF.

    NOTA BENE:This solution implies at least one running webbrowser, but gives you real control and testing over the resulting page.

    UPDATE2: Well seems NS4 was also the last browser to support link-coordinates, but I'm sure that standard DOM has even much richer possibilities. ... indeed style.left, or offsetLeft, offsetTop

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://779235]
Approved by Old_Gray_Bear
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (6)
As of 2021-04-14 05:08 GMT
Find Nodes?
    Voting Booth?

    No recent polls found