[reportlab-users] Bounded text (truncated)

Robin Becker robin at reportlab.com
Thu Jan 4 09:36:51 EST 2007


Michael Hipp wrote:

> Hello,

>

> I'm fairly new to ReportLab. Thanks for a great tool.

>

> I'm trying to find a way to print "bounded" text. Meaning I want the "field"

> it is printed in to be a certain specified size and never exceed that size. If

> a text value is printed that would go beyond that size, then the text should

> be truncated.

>

> Is there some simple way to accomplish this?

......

Maybe not simple. There are ways to do this for two cases. One where you just
want a single line of text and another where you want something like a paragraph
with specified width.

In the first case it would be something like this.

from reportlab.pdfbase.pdfmetrics import stringWidth
t = "this is my very long and disreputable text ... boring etc etc etc"
fontName='Times-Roman'
fontSize=12
desired = 2*72 # two inches
while t and stringWidth(t,fontName,fontSize)>desired:
t = t[:-1]

print t

which eventually prints "this is my very long and disre". This could better be
done using binary search, but that I leave as an exercise.

The paragraph case can be treated similarly, but it's probably worth doing more
efficiently using the built in mechanisms of paragraphs.

########################
text = """this is my very long and disreputable text ... boring etc etc etc I go
on and on and on for days and weeks and months"""

from reportlab.platypus.paragraph import Paragraph
from reportlab.lib.styles import ParagraphStyle
normal = ParagraphStyle('normal')
normal.firstLineIndent = 18
normal.spaceBefore = 0
normal.spaceAfter = 0
dW = 2*72 #2 inches
dH = 0.5*72 #0.5 inch
para = Paragraph(text,normal)
w,h = para.wrap(dW,dH)

print 'desired=%sx%s wanted=%sx%s' % (dW,dH,w,h)
if h>dH+1e-8:
S = para.split(dW,dH)
print 'split returned %d elements' % len(S)
if len(S)>=1:
para = S[0]
w,h = para.wrap(dW,dH)
print 'desired=%sx%s new wanted=%sx%s' % (dW,dH,w,h)
print '\n'.join([' '.join(x[1]) for x in para.blPara.lines])
else:
print "can't hack that paragraph into size"
--
Robin Becker


More information about the reportlab-users mailing list