[reportlab-users] Printing Variable Length String

Tim Roberts timr at probo.com
Wed Nov 7 17:00:35 EST 2007


Rich Shepard wrote:

> On Sun, 4 Nov 2007, timr at probo.com wrote:

>

>> ... but it really isn't that hard to do word-wrapping on your own. You

>> can split() the string on white space, and keep adding words one at a

>> time

>> until the stringWidth() exceeds the length you want, and then back

>> off one

>> word.

>

> Has anyone a working algorithm to do this? The one I'm working on seems

> excessively bulky and complex; I'm sure there's an easier way.


No, bulky is pretty much the rule. Here's what I use. This accepts a
string, a canvas, and a width, and returns a list of strings, each of
which is smaller than "width".

def wrap( strg, cvs, width ):
fn = cvs._fontname
fs = cvs._fontsize
if cvs.stringWidth( strg, fn, fs ) <= width:
return [strg]

accum = []
s = ''
for i in strg.split():
if cvs.stringWidth( s+i, fn, fs ) > width:
accum.append( s )
s = ''
if s:
s = ' '.join( (s, i) )
else:
s = i
if s:
accum.append( s )
return accum

Support for extra spaces after full stops is left as an exercise for the
reader.

--
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the reportlab-users mailing list