[reportlab-users] Truncate table cell content to end with ellipsis

Robin Becker robin at reportlab.com
Mon Apr 20 08:51:04 EDT 2009


Yves Forkl wrote:

> Robin Becker schrieb:

>>

>> if you cannot use the broken fragline stuff to locate the position

>> where the text should be ended then you'll need to brute force the

>> search. A good approach uses a binary search to determine where the

>> split should occur eg [...]

>

> Thank you for the function locateSplit you proposed. In the meantime, I

> had come up with a function that follows very much the same line of

> thought (but shortens and appends the ellipsis as well):

>

> def fitIntoTableCell(content, columnWidth, fontName, fontSize):

> _c = canvas.Canvas('nofile.pdf')

> # reduce actual column width a bit, to account for padding etc.

> columnWidth -= 5

> contentWidth = _c.stringWidth(content, fontName, fontSize)

> shortened = False

> # if the content is wider than the cell, cut off enough from it so

> # that the ellipsis fits in, too

> if contentWidth > columnWidth:

> shortened = True

> # take width of ellipsis into account; empirically determined

> # with fontName == Helvetica and fontSize == 12 (should

> # rather be calaculated from these parameters)

> columnWidthBeforeEllipsis = columnWidth - 7

> while contentWidth > columnWidthBeforeEllipsis:

> # cutting by single characters because words might be too

> # long

> content = content[:-1]

> contentWidth = _c.stringWidth(content, fontName, fontSize)

> del _c

> if shortened:

> content += u'\u2026'

> return content

>

> I wonder how I could do without the dummy canvas, though...

>

> Yves

........
you can import stringWidth directly eg

from reportlab.pdfbase.pdfmetrics import stringWidth

then change _c.stringWidth to stringWidth

--
Robin Becker


More information about the reportlab-users mailing list