Python Reportlab PDF - 在页面上居中文本

16

我正在使用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)

文本显示出来了,我可以手动移动左侧的位置使文本看起来居中,但由于文本是动态的且我不知道将有多少文本,因此需要通过编程来实现居中显示。

5个回答

18

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

我们是英国人,该死的,我们为自己的拼写感到骄傲!

编辑:至于文本对象,抱歉没有。不过你可以尝试类似以下的内容:

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.

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


谢谢Jim,我使用了 p.drawCentredString(4.25*inch, 500, 'some text') 这个很好用,但是我该如何在.textOut或.textLine中使用drawCentredString? p.drawCentredString(center, 500, header); - jhanifen
defaultPageSize 不在其他地方。导入语句是 from reportlab.rl_settings import defaultPageSize - joeyagreco

7

我也需要这个,于是写了这个:


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

+1,如果使用canvas.beginText() :) 旧的回答,但它的效果非常好!然后,您需要在画布上绘制返回到画布的tx。例如:my_canvas.drawText(createTextObject(my_canvas, x, y, text, style, centered)) - teewuane

4
您可以使用如段落的Flowable对象,并将对齐方式的值分配为1:
styles = getSampleStyleSheet()
title_style = styles['Heading1']
title_style.alignment = 1
title = Paragraph("Hello Reportlab", title_style)
story.append(title)

这个例子将创建一个带有居中文本的PDF文档:

from flask import make_response
import io
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet

story=[]
pdf_doc = io.BytesIO()
doc = SimpleDocTemplate(pdf_doc)

styles = getSampleStyleSheet()
title_style = styles['Heading1']
title_style.alignment = 1
title = Paragraph("Hello Reportlab", title_style)
story.append(title)
doc.build(story)

content = pdf_doc.getvalue()

#output to browser
response = make_response(content)
response.mimetype = 'application/pdf'
return response

如果您想要文本向左浮动,您需要将alignment更改为0:
title_style.alignment = 0

如果您希望文本向右浮动,您需要将alignment更改为2:

title_style.alignment = 2

0
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
doc = SimpleDocTemplate("form_letter.pdf",pagesize=letter,
                        rightMargin=72,leftMargin=72,
                        topMargin=72,bottomMargin=18)
Story = []
styles = getSampleStyleSheet()
title_style = styles['Heading1']
title_style.alignment = 1
title = Paragraph("Welcome to india", title_style)
Story.append(title)
doc.build(Story)

0

1
请将解决方案复制到您的答案中。外部参考资料也可以作为额外的解释。 - taras

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接