Thomas Kremmel
Thomas Kremmel

Reputation: 14783

reportlab set left table position

How can I set the left position of a table?

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)

Whereas the paragraph is printed one cm from the left, table is printed with almost no distance to the left page border.

Where do I have to set the leftMargin for the table position?

The same is valid for images I add. They seem to be printed somewhere.

story.append(Image(path,35,10))

Upvotes: 4

Views: 11677

Answers (2)

Crebit
Crebit

Reputation: 377

I would like to add that you can also set the alignment in TableStyle just like you set the lineabove and linebelow.

While this may not be valuable information in itself, it is important to know that horizontal alignment is set with keyword 'ALIGN' and not 'HALIGN' (as you would easily assume given that vertical alignment is set with 'VALIGN' and the above solution also has hAlign in the function call). I went mad trying to align stuff with 'HALIGN' all day.

Below is a code sample where you can test the horizontal alignment ('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

Upvotes: 2

Thomas Kremmel
Thomas Kremmel

Reputation: 14783

Found the magic hAlign keyword:

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

Upvotes: 20

Related Questions