在 Reportlab 中拉伸 table 列

Stretch table column in Reportlab

我正在尝试在 Reportlab(不是 RML)中拉伸 table 列,我试过像这样设置 colWidths:

tab = Table(data, colWidths=["*", None, None, None, None, None])

如文档中所写,但第一列的大小没有改变(它保持在 "size-to-contents")。有什么方法可以使第一列伸展到可用 space,而无需指定固定大小? (因为其他列 根据某些参数动态变化)

这似乎是 Reportlab 的故意行为,因为宽度计算代码是这样说的:

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'''

这意味着 *None 不能在宽度列表中一起使用,这没有意义,因为这样一列如何拉伸而另一列是大小到内容。无论如何,我最终写了一个包装函数,re-calculates 一切:

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

丑陋但对我有用。如果需要,可以扩展它以支持多个 * 列。