I am Creating a table with reportlab, I want to align a single cell (to the right) in the following table:
I want to align the cell containing "Occupation" to right
This is my code:
studentProfileData = [
['Application Form No', ''],
['Name', userData['studentDetails']["firstName"] + " " +userData['studentDetails']["lastName"]],
['Course opted for', userData['courseDetails']["courseOptedFor"]],
['Specific Course Name', courseMapping["Name"]],
['Category', userData['studentDetails']['caste']],
['Religion', userData['studentDetails']['religion']],
['Fathers'+ "'" +'s Name', userData['studentDetails']['religion']],
['Occupation', userData['studentDetails']['fOccupation']],
['Phone No', ""],
['Term', ""]
]
colwidths = [3 * inch, 1.5 * inch, inch]
# Two rows with variable height
rowheights = [.5*inch] * len(studentProfileData)
studentProfile = Table(studentProfileData, colwidths, rowheights, hAlign='LEFT')
studentProfile.setStyle(TableStyle([
('ALIGN', (0, 0), (0, -1), "LEFT"),
('FONTSIZE', (0,0), (-1, -1), 13),
]))
parts = [ page1Head, studentProfile]
In order to align a single cell in a Reportlab Table
we need to change the TableStyle
to the following:
TableStyle([
('ALIGN', (0, 0), (0, -1), "LEFT"),
('FONTSIZE', (0,0), (-1, -1), 13),
('ALIGN', (0, 7), (0, 7), "RIGHT"),
])
This works because we now tell that cells in the area between (0,7)
and (0,7)
should be aligned right, as the only cell in that area is the cell containing Occupation
only that text is aligned.
An alternative approach is to use a Paragraph
instead of just a String
in the table, in that case we can do the alignment with the Paragraph
as it will fill the complete width of the cell.
Paragraph Example
pageTextStyleCenter = ParagraphStyle(name="left", alignment=TA_CENTER, fontSize=13, leading=10)
[ Paragraph("Occupation", pageTextStyleCenter) , userData['studentDetails'].get('fOccupation', "-")]