Python Reportlab PDF-将文本居中放置在pag上

2024-06-26 01:38:37 发布

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

我正在使用ReportLab使用python动态生成pdf。

我想要一行文字在一页上居中。这是我目前拥有的特定代码,但不知道如何水平居中文本。

header = p.beginText(190, 740)
header.textOut("Title of Page Here")

# I know i can use TextLine etc in place of textOut

p.drawText(header)

文本显示出来,我可以手动移动左边的位置,使文本看起来居中,但我需要这是以编程方式居中,因为文本将是动态的,我不知道会有多少文本。


Tags: of代码文本herepdftitlepage水平
3条回答

reportlab画布有一个drawCentredString方法。是的,他们这样拼写。

We’re British, dammit, and proud of our spelling!

编辑: 至于文本对象,恐怕你没有。不过,你可以这样做:

from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.rl_config import defaultPageSize

PAGE_WIDTH  = defaultPageSize[0]
PAGE_HEIGHT = defaultPageSize[1]

text = "foobar foobar foobar"
text_width = stringWidth(text)
y = 1050 # wherever you want your text to appear
pdf_text_object = canvas.beginText((PAGE_WIDTH - text_width) / 2.0, y)
pdf_text_object.textOut(text) # or: pdf_text_object.textLine(text) etc.

显然,您可以使用其他页面大小。

我也需要这个,然后写了这个:

def createTextObject(canv, x, y, text, style, centered=False):
    font = (style.fontName, style.fontSize, style.leading)
    lines = text.split("\n")
    offsets = []
    if centered:
        maxwidth = 0
        for line in lines:
            offsets.append(canv.stringWidth(line, *font[:2]))
        maxwidth = max(*offsets)
        offsets = [(maxwidth - i)/2 for i in offsets]
    else:
        offsets = [0] * len(lines)
    tx = canv.beginText(x, y)
    tx.setFont(*font)
    for offset, line in zip(offsets, lines):
        tx.setXPos(offset)
        tx.textLine(line)
        tx.setXPos(-offset)
    return tx

尝试:

<para alignment="center">

根据参考:http://two.pairlist.net/pipermail/reportlab-users/2006-June/005092.html

就你而言:

header.textOut("<"para alignment='center'>"Title of Page Here")

相关问题 更多 >