How to calculate the amount of space taken by a given text?

How to calculate the amount of space taken by a given text?

Post by Stefan Wal » Fri, 14 Jul 2006 17:48:48


Hello Everyone,

in a Java web application, a user can enter a text (HTML textarea) which
is then sent to a Servlet. This text should later appear in a Text Box
of a PowerPoint presentation, which can be downloaded by the user. The
width of the Text Box is fixed, as is the font type and size in which
the text should appear (it's a true type font).

To get the text into the PowerPoint Text box is not the problem; for
this we are using a commercial PPT library by tonic systems.

However, the Servlet should send a warning message to the user, if the
text given by him wouldn't fit into the PowerPoint Text Box. If too much
text is given, the Box would automatically extend downwards, and the
text would overlap with the text from another Text Box below. But this
should not happen, so in this case the warning should be displayed.

Does anyone have an idea how to do a calculation if the given text would
fit into the box or if it wouldn't? The problem is that the text can
wrap automatically when it hits the rightmost boundary of the box, and
that the letters of a TrueType font have different widths; so a
calculation based on newlines and number of characters wouldn't work.

I would be grateful for any hint or suggestion (or even a ready solution
;-) how to solve this problem


Thanks and regards
Stefan
 
 
 

How to calculate the amount of space taken by a given text?

Post by Andrew T » Fri, 14 Jul 2006 18:26:36


...
...

Assuming you can get a Font object of this TrueType font, the
java.awt.FontMetrics.stringWidth(java.lang.String) method
should give you the 'length of a piece of string'.

Andrew T.