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

I'm writing a program that generates reports from a database. The reports consist of a grid of images with textual information about each image centered above the image. For various reasons, I'm using SVGs as templates for the reports which I'm then modifying using HTML::Template.

My problem is that I need to be able to center the text above each image. I know exactly where each image will be placed, but since I don't know how wide the text will be, I don't know where to place it relative to the image. In some cases the text might only be a single word; in other cases it could be five times that long. Is there a way to calculate SVG text widths? Any other ideas about how I can center the text?

Thanks in advance,

--TWH

Replies are listed 'Best First'.
Re: SVG text width calculation
by roboticus (Chancellor) on Dec 29, 2010 at 20:46 UTC
Re: SVG text width calculation
by Anonyrnous Monk (Hermit) on Dec 29, 2010 at 21:13 UTC

    Use the attribute text-anchor="middle" instead of computing the width yourself (which is hard to do as you usually wouldn't easily get at the individual glyphs' widths of the particular font being used).

    Here's an example that centers text above a rectangle:

    <?xml version="1.0" encoding="UTF-8"?> <svg version="1.2" width="100%" height="100%" viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg"> <g transform="translate(100 100)"> <rect width="200" height="50" x="-100" y="10" fill="lightyellow"/> <text text-anchor="middle">Some centered text</text> </g> </svg>

    (tested with Firefox 3.6.8 and Opera 10.63)

      This is indeed the best solution, though one has to be aware that client support for text anchors isn't generally very good - last I tried inkscape didn't recognize it.

      While SVG is a very nice format, and easy to generate, client side support is as unreliable as web programming in the days where you had to support IE 4 to 6 and all the "normal" browsers too. (I've ranted about this before).

      Another possible approach (but clearly inferior to text-anchor) is to estimate the length of the rendered text (for example with help of Font::TTFMetrics), and then fixing the length to the calculated value with the textLength attribute. But then again this often results in ugly output, and the client support for textLength is equally bad.

      Thanks! That did the trick.
Re: SVG text width calculation
by Corion (Patriarch) on Dec 29, 2010 at 20:43 UTC

    You don't say in what unit you want to measure the width. Using Inkscape, you could render (the relevant part of) your SVG into a bitmap and then look at how wide it is. There also is SVG::Rasterize, but I haven't used it.

      I hear Inkscape has tools to measure angles and distance