reportlab设置左表位置

时间:2012-08-05 18:30:28

标签: reportlab

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

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))

2 个答案:

答案 0 :(得分:9)

找到了神奇的hAlign关键字:

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

答案 1 :(得分:1)

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

虽然这本身可能不是有价值的信息,但重要的是要知道水平对齐是用关键字' ALIGN'设置的。而不是' HALIGN' (因为您可以轻松假设垂直对齐是使用' VALIGN' 设置的,并且上述解决方案也有hAlign in函数调用)。我疯了,试图把东西与'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