19

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?

4

3 回答 3

18

基本上你只需要计算字符串的宽度,你想要居中的区域的宽度,你就完成了。

使用Canvas.stringWidth确定给定字符串(带有字体和大小)占用的宽度。它没有考虑字符间距,但我做了一些测试表明可以解决这个问题。

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

它所做的只是使用原始stringWidth来计算字符串的宽度,并在字符之间添加额外的空格。现在我对排版没有经验,所以我不确定像字距调整这样的字体功能是否会导致它无法使用。

如果您像这样调整 x 原点,您的字符串将居中。

(area_width - string_width) / 2

我使用的小测试脚本http://pastebin.com/PQxzi1Kf(代码不是美女,但可以)。

于 2011-02-11T18:13:30.233 回答
3

Reportlab 有一个方法,drawCentredString(以英式拼写为中心)。这将使您的文本沿给定的 x 坐标居中。

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

于 2015-08-09T18:50:36.553 回答
-1

尝试:<para alignment="center">来自:http ://two.pairlist.net/pipermail/reportlab-users/2006-June/005092.html

于 2017-05-21T19:23:50.070 回答