21

I have the following ReportLab code:

    t = c.beginText()
    t.setFont('Arial', 25)
    t.setCharSpace(3)
    t.setTextOrigin(159,782)
    t.textLine("Some string")
    c.drawText(t)

What I want to achieve is: have a 3 (pixels?) space between each character (setCharSpace), and align the resulting string in the center of a certain area in the page

The textobject is the only way, as far as I found, that I can specify a space between characters.

Any ideas?

Nicu Surdu
  • 8,172
  • 9
  • 68
  • 108

3 Answers3

19

Basically you only have to calculate the width of the string, the width of the area where you want to center it, and you're done.

Use Canvas.stringWidth to determine the width a given string (with a font and size) occupies. It doesn't take char spacing into account, but I did some tests that suggests one can fix that.

def stringWidth2(string, font, size, charspace):
    width = stringWidth(string, font, size)
    width += (len(string) - 1) * charspace
    return width

All it does is using the original stringWidth to calculate the width of the string, and add the additional spaces between the characters. Now I'm not experienced with typography, so I'm not sure if font features like kerning may render this unusable.

If you adjust your x origin like this, your string will be centered.

(area_width - string_width) / 2

Small test script I used http://pastebin.com/PQxzi1Kf (code is not a beauty, but it works).

Reiner Gerecke
  • 11,936
  • 1
  • 49
  • 41
  • 1
    I think that stringWidth has since been updated since 2011 and now incorporates the character spacing. – Usagi Mar 02 '18 at 06:01
6

Reportlab has a method, drawCentredString (centred for British spelling). This will center your text along the given x coordinate.

http://www.reportlab.com/apis/reportlab/2.4/pdfgen.html

strongriley
  • 1,093
  • 1
  • 15
  • 12
-1

Try: <para alignment="center"> From: http://two.pairlist.net/pipermail/reportlab-users/2006-June/005092.html

Nicu Surdu
  • 8,172
  • 9
  • 68
  • 108
Santiago M. Quintero
  • 1,237
  • 15
  • 22