PythonReportLab PDF-将文本置于页面中心
我正在使用python动态生成pdf 我想在一页上居中放置一行文字。下面是我目前拥有的特定代码,但不知道如何水平居中文本PythonReportLab PDF-将文本置于页面中心,python,pdf-generation,reportlab,Python,Pdf Generation,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) 文本显示,我可以手动向左移动,使文本看起来居中,但我需要以编程方式居中,因为文本是动态的,我不
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)
文本显示,我可以手动向左移动,使文本看起来居中,但我需要以编程方式居中,因为文本是动态的,我不知道会有多少文本。reportlab画布有一个方法。是的,他们是这样拼写的 我们是英国人,该死的,我们以 我们的拼写 编辑: 至于文本对象,恐怕你没有。不过,您可以按照这些思路做一些事情:
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
尝试:
根据参考资料:
就你而言:
header.textOut("<"para alignment='center'>"Title of Page Here")
header.textOut(“您可以使用可流动对象,如段落
,并将对齐
值指定给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
如果希望文本向左浮动,则需要将对齐方式更改为0:
title_style.alignment = 0
如果希望文本向右浮动,则需要将对齐方式更改为2:
title_style.alignment = 2
谢谢Jim,我使用了p.drawCentredString(4.25*inch,500,“一些文本”),效果很好,但是如何将drawCentredString与.textOut或.textLine一起使用呢?p.drawCentredString(中心,500,标题);+1用于使用canvas.beginText:)旧答案,但效果很好!您确实需要绘制返回画布的tx
。如my_canvas.drawText(createTextObject(my_canvas,x,y,text,style,居中))
请将解决方案复制到您的答案中。外部引用很好,只是作为额外的解释。
title_style.alignment = 2