[reportlab-users] Dot separators in text

Tim Roberts timr at probo.com
Fri Dec 1 13:35:50 EST 2006


Jim Steil wrote:

>

> Hi,

>

>

>

> I’m trying to create a PDF that has a table in it that looks like the

> attached picture. Can anyone point me down the right path to get the

> dot separators between the two ends of the line? The width of the

> text on both ends of the line may vary and I’d prefer to not have to

> calculate how many dots need to be included so that both the right and

> left edges are justified.

>

>

>

> Thanks!

>

>

>

> -Jim

>

>

>


There are some decisions you have to make. For example, how much space
do you want to leave between the strings and the dots? How do you want
the dots to line up? If the right side is variable size, do you want
the dots to all end at the same place, or to end a certain distance from
the string? Remember that a list like this tends to look bad unless the
dots all line up vertically. That can be tricky.

It would be fun to try to write a generalized tab expander. Hmm...
Maybe I'll think about that.

Here is a sample. This leaves exactly one space on the right end, and
one space plus the rounding on the left end.

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import LETTER
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

pdfmetrics.registerFont( TTFont( 'Arial', 'arial.ttf'))
pdfmetrics.registerFont( TTFont( 'Narrow', 'arialn.ttf'))
pdfmetrics.registerFont( TTFont( 'ArialBlack', 'ariblk.ttf'))

def DotTab( canv, x, y, w, txt ):
# How big is a space?
space = canv.stringWidth( ' ', canv._fontname, canv._fontsize )

# How big is a dot?
dot = canv.stringWidth( '.', canv._fontname, canv._fontsize )

# Break the string into two pieces.
parts = txt.split('\t')
leftw = canv.stringWidth( parts[0], canv._fontname, canv._fontsize )
rightw = canv.stringWidth( parts[1], canv._fontname, canv._fontsize )

# How much space do I have to fill?
extra = w - leftw - rightw

# How many whole dots will that take?
dots = int((extra - space - space) / dot)

# How much space do I need between the left string and the dots?
extra -= dots * dot + space

canv.drawString( x, y, parts[0] )
canv.drawString( x+leftw+extra, y, '.'*dots )
canv.drawRightString( x+w, y, parts[1] )


canv = canvas.Canvas( 'dots.pdf', pagesize=LETTER )
canv.setPageCompression( 0 )
canv.setFont( 'Arial', 14 )

width=288
DotTab( canv, 72, 144, width, 'Drummers drumming\t12' )
DotTab( canv, 72, 128, width, 'Pipers piping\t11' )
DotTab( canv, 72, 112, width, 'Lords a leaping\t10' )
DotTab( canv, 72, 96, width, 'Ladies dancing\t9' )
DotTab( canv, 72, 80, width, 'Maids a milking\t8' )
DotTab( canv, 72, 64, width, 'Swans a swimming\t7' )
DotTab( canv, 72, 48, width, 'Geese a laying\t6' )
DotTab( canv, 72, 32, width, 'Golden rings\t5' )

canv.showPage()
canv.save()

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



More information about the reportlab-users mailing list