Python ReportLab使用splitfirst / splitlast
我正在尝试将Python与ReportLab 2.2一起使用以创建PDF报告。
根据用户指南,
Special TableStyle Indeces [sic] In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.
我尝试使用几种样式元素,包括:
('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black)
这些似乎都不起作用。第一个生成带有消息的TypeError:
TypeError: cannot concatenate 'str' and 'int' objects
后两个消息生成TypeErrors:
TypeError: an integer is required
该功能只是被破坏还是我做错了什么?如果是后者,我在做什么错?
解决方案
回答
[...] In any style command the first row index may be set to one of the special strings [...]
在第一个示例中,我们还将第二行索引设置为特殊字符串。
不知道为什么其他两个都不起作用...我们确定这是异常的来源吗?
回答
好吧,看来我将回答自己的问题。
首先,文档应整齐地显示为"在任何样式命令中,第一行索引都可以设置为特殊字符串'splitlast'或者'splitfirst'中的一个,以指示该样式仅应用于拆分表,或者连续的第一行。"在当前版本中," splitlast"和" splitfirst"行索引在TEXTCOLOR和Background commnds上出现上述TypeErrors错误。
基于读取源代码,我的怀疑是当前只有表格样式行命令(GRID,BOX,LINEABOVE和LINEBELOW)与'splitfirst'和'splitlast'行索引兼容。我怀疑所有单元格命令都会因上述TypeErrors而中断。
但是,我可以通过继承Table类并覆盖onSplit方法来实现自己想要的功能。这是我的代码:
class XTable(Table): def onSplit(self, T, byRow=1): T.setStyle(TableStyle([ ('TEXTCOLOR', (0, 1), (1, 1), colors.black)]))
这是将文本颜色黑色应用于每页第二行的第一和第二个单元格。 (第一行是表头,由Table的repeatRows参数重复。)更确切地说,它是对每个帧的第一和第二个单元格执行此操作,但是由于我使用的是SimpleDocTemplate,因此帧和页面是相同的。
回答
这似乎是ReportLab Table类中的错误。除了DLJessup自己的答案外,另一个解决方法是在行1301的" Table._drawBkgrnd()"中修改导致错误的ReportLab代码。对于" splitlast",请更改:
y0 = rowpositions[sr]
到:
if sr == 'splitlast': y0 = rowpositions[-2] # last value is 0. Second last is the one we want. else: y0 = rowpositions[sr]
这可以通过我们自己的代码轻松完成,而无需通过继承Table的子类并覆盖此方法来入侵ReportLab。我不需要使用" splitfirst";如果我愿意,我将在此处发布其余的hack。