I'm trying to stretch a table column in Reportlab (not RML), I've tried setting colWidths like this:
tab = Table(data, colWidths=["*", None, None, None, None, None])
as written in the documentation, but the size of the first column doesn't change (it stays on "size-to-contents"). Is there any way to make the first column stretch to available space, without specifying a fixed size? (since the other columns will change dynamically depending on some parameters)
This seems to be a deliberate behavior of Reportlab, since the width calculation code says this:
def _calc_pc(V,avail):
'''check list V for percentage or * values
1) absolute values go through unchanged
2) percentages are used as weights for unconsu
3) if no None values were seen '*' weights are
set equally with unclaimed space
otherwise * weights are assigned as None'''
Which means that *
and None
can't be used together in the list of widths, which doesn't make sense because then how do you make a column stretch while the other are sized to content. Anyways, I ended up writting a wrapper function that re-calculates everything:
def table_fix(data, cols, total):
table = Table(data, colWidths=cols)
res = list(cols)
val = table._cellvalues
style = table._cellStyles
while None in res:
idx = res.index(None)
width = 0
for i, vi in enumerate(val):
v = vi[idx]
s = style[i][idx]
nw = table._elementWidth(v, s) + s.leftPadding + s.rightPadding
if nw > width:
width = nw
res[idx] = width
table._colWidths = table._argW = res
return table
Ugly but does the job for me. It can be extended to support multiple *
columns if need be.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.