reportlab TableStyle 中的 VALIGN 显然没有效果
VALIGN in reportlab TableStyle apparently without effect
所以,一段时间以来,我一直在为这个问题苦苦挣扎。我知道有很多类似的问题都有很好的答案,我也尝试过这些答案,但我的代码基本上反映了给出的答案。
我正在编写代码来自动生成工作表的匹配练习。所有这些信息都应该在 table 中。并且文本应全部对齐到单元格的顶部。
这是我现在拥有的:
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import cm
document = []
doc = SimpleDocTemplate('example.pdf', pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72)
styles = getSampleStyleSheet()
definitions = []
i, a = 1, 65
table = []
for x in range(1, 10):
line = []
line.append(Paragraph(str(i), styles['BodyText']))
line.append(Paragraph('Vocabulary', styles['BodyText']))
line.append(Paragraph(chr(a), styles['BodyText']))
line.append(Paragraph('Often a multi-line definition of the vocabulary. But then, sometimes something short and sweet.', styles['BodyText']))
table.append(line)
i += 1
a += 1
t = Table(table, colWidths=(1*cm, 4*cm, 1*cm, None))
t.setStyle(TableStyle([
('VALIGN', (1, 1), (-1, -1), 'TOP')
]))
document.append(t)
doc.build(document)
我忽略了什么?
问题在于您索引 TableStyle
的方式。 Reportlab 中的索引从第一行第一列的 (0, 0)
开始。因此,在您的情况下,(1, 1)
仅将样式应用于第一行下方和第一列右侧的所有内容。
正确的方法是使用:
('VALIGN', (0, 0), (-1, -1), 'TOP')
这会将样式应用于 Table
中的所有单元格。
所以,一段时间以来,我一直在为这个问题苦苦挣扎。我知道有很多类似的问题都有很好的答案,我也尝试过这些答案,但我的代码基本上反映了给出的答案。
我正在编写代码来自动生成工作表的匹配练习。所有这些信息都应该在 table 中。并且文本应全部对齐到单元格的顶部。
这是我现在拥有的:
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import cm
document = []
doc = SimpleDocTemplate('example.pdf', pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72)
styles = getSampleStyleSheet()
definitions = []
i, a = 1, 65
table = []
for x in range(1, 10):
line = []
line.append(Paragraph(str(i), styles['BodyText']))
line.append(Paragraph('Vocabulary', styles['BodyText']))
line.append(Paragraph(chr(a), styles['BodyText']))
line.append(Paragraph('Often a multi-line definition of the vocabulary. But then, sometimes something short and sweet.', styles['BodyText']))
table.append(line)
i += 1
a += 1
t = Table(table, colWidths=(1*cm, 4*cm, 1*cm, None))
t.setStyle(TableStyle([
('VALIGN', (1, 1), (-1, -1), 'TOP')
]))
document.append(t)
doc.build(document)
我忽略了什么?
问题在于您索引 TableStyle
的方式。 Reportlab 中的索引从第一行第一列的 (0, 0)
开始。因此,在您的情况下,(1, 1)
仅将样式应用于第一行下方和第一列右侧的所有内容。
正确的方法是使用:
('VALIGN', (0, 0), (-1, -1), 'TOP')
这会将样式应用于 Table
中的所有单元格。