reportlab设置左表位置

问题描述 投票:1回答:2

如何设置表格的左侧位置?

response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
buffer = StringIO()
PAGESIZE = pagesizes.portrait(pagesizes.A4)
doc = SimpleDocTemplate(buffer, pagesize=PAGESIZE, leftMargin=1*cm)
story = []

story.append(Paragraph(header_part2, styleN))
table_row = ['Total Score:','']
data.append(table_row)
ts = [
    #header style    
    ('LINEABOVE', (0,0), (-1,0), 1, colors.gray),
    ('LINEBELOW', (0,0), (-1,0), 1, colors.gray)]
t = Table(data, (6*cm,6*cm), None, style=ts)
    story.append(t)
    doc.build(story)
    pdf = buffer.getvalue()
buffer.close()
response.write(pdf)

虽然段落打印在距离左侧一厘米处,但打印的表格与左页边框几乎没有距离。

我在哪里为表位置设置leftMargin?

这同样适用于我添加的图像。他们似乎在某处打印。

story.append(Image(path,35,10))
reportlab
2个回答
9
投票

找到了神奇的hAlign关键字:

t = Table(data, (6*cm,6*cm,2*cm,2*cm,2*cm), None, style=ts, hAlign='LEFT')

1
投票

我想补充一点,你也可以在TableStyle中设置对齐,就像设置lineabove和linebelow一样。

虽然这本身可能不是有价值的信息,但重要的是要知道水平对齐是使用关键字'ALIGN'设置而不是'HALIGN'(因为您可以轻松假设垂直对齐设置为'VALIGN'和上述解决方案也有函数调用中的hAlign)。我疯狂地试图整天与'HALIGN'对齐。

下面是一个代码示例,您可以在其中测试水平对齐('ALIGN')。

from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus.tables import Table, TableStyle
from reportlab.lib import colors

doc = SimpleDocTemplate('align.pdf', showBoundary=1)

t = Table((('', 'Team A', 'Team B', 'Team C', 'Team D'),
   ('Quarter 1', 100, 200, 300, 400),
   ('Quarter 2', 200, 400, 600, 800),
   ('Total', 300, 600, 900, 1200)),
  (72, 45, 45, 45, 45),
  (25, 15, 15, 15)
  )

t.setStyle(TableStyle([
   ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
   ('GRID', (0, 0), (-1, -1), 0.25, colors.red, None, (2, 2, 1)),
   ('BOX', (0, 0), (-1, -1), 0.25, colors.blue),
   ]))

story = [t]
doc.build(story)

Resulting table in pdf

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