Python Reportlab PDF - 将页面上的文本居中

问题描述 投票:0回答:6

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

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

python pdf-generation reportlab
6个回答
18
投票

reportlab 画布有一个 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.

显然,您可以使用其他页面尺寸。


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

4
投票

您可以使用像

Paragraph
这样的Flowable对象并将
alignment
值分配给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
投票

尝试:

<para alignment="center">

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

您的情况:

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

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
投票

我想出的简单解决方案,以任意长度动态居中标题:

from textwrap import wrap


address = '12 Grimmauld Place, London, England, United Kingdom, Wizarding World'

for i, s in enumerate(wrap(address, 20)):
    y_step  = 10 * i
    y_start = 560 - y_step
    pdf.drawCentredString(x_center, y_start, s)

生成的 pdf:

Result

© www.soinside.com 2019 - 2024. All rights reserved.