Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReportLab: How to align a textobject?

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?

like image 298
Nicu Surdu Avatar asked Feb 11 '11 15:02

Nicu Surdu


2 Answers

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).

like image 185
Reiner Gerecke Avatar answered Sep 21 '22 20:09

Reiner Gerecke


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

like image 24
strongriley Avatar answered Sep 19 '22 20:09

strongriley