The best suggestion I know of is to use Font::TTFMetrics (if you are using TrueType fonts or can find/convert your font to an equivalent), or Image::Magick for other font types. You would then probably have to go word by word (or break-by-break if you're using hyphenation) and calculate the length. The other option would be to use a D&C algorithm and keep splitting the string until it falls within the desired min/max width. With Font::TTFMetrics, you can calculate the width of a string something like so:

use Font::TTFMetrics; my $resolution = 72; # 72dpi typical, 96, 100, 120 common my $pointsize = 12; # Whatever size the target text is my $string = 'Some string'; my $font = Font::TTFMetrics->new('/path/to/Font.ttf'); my $font_units = $font->string_width($string); my $pixels = $font_units * $pointsize * $resolution / (72 * $font->get_units_per_em); printf "Width of `%s' is %.2f font units, or %d pixels\n", $string, $font_units, $pixels;

Hope this helps!


In reply to Re: Formatting block of text by rjt
in thread Formatting block of text by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.