如何确定 reportlab 中旋转文本的长度

2024-09-26 22:10:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用画布.stringWidth计算句子的长度报告实验室。但是当我旋转大标记时,它会用计算的宽度来包装文本,而不是旋转的文本。代码段是

text_len = canvas.stringWidth("Hello" , "Helvetica", 10)
canvas.rotate(rotation)
P.drawOn(canvas, 0, 0)

它适用于直接文本,但对于旋转文本则不起作用。在


Tags: text标记文本hellolen宽度代码段画布
1条回答
网友
1楼 · 发布于 2024-09-26 22:10:56

代码的问题是canvas.stringWidth(self, text, fontName, fontSize)返回给定字符串的宽度而不进行包装。因此,旋转画布不会减小宽度,因为字符串的长度仍然相同。在

为了说明这一点,让我们看看以下示例:

def rotated_text_length(c, string):
    text_len = c.stringWidth(string, "Helvetica", 10)
    print "Normal text: ", text_len

    c.rotate(90)
    text_len = c.stringWidth(string, "Helvetica", 10)
    print "Rotated text: ", text_len

c = canvas.Canvas("hello.pdf")
rotated_text_length(c, "This is a very silly example"*100)
rotated_text_length(c, "This is a very silly example"*50)

如果字符串宽度可以换行,则两个旋转句子的长度相同,但输出如下:

^{pr2}$

这表示返回的宽度只取决于字符串长度(当然还有字体)。因此,基于Reportlab引用,不应用任何包装:

def stringWidth(self, text, fontName=None, fontSize=None):

gets width of a string in the given font and size

相关问题 更多 >

    热门问题