Reportlab:使用Table和SPAN

时间:2011-11-01 08:37:44

标签: python html reportlab

示例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.lib.pagesizes import letter

def testPdf():
    doc = SimpleDocTemplate("testpdf.pdf",pagesize=letter,
                        rightMargin=72,leftMargin=72,
                        topMargin=72,bottomMargin=18)
    elements = []
    datas = []
    for x in range(1,50):
        datas.append(
            [x,x+1]
        )
    t=Table(datas)
    tTableStyle=[
        ('SPAN',(0,0),(0,37)),
      ]
    t.setStyle(TableStyle(tTableStyle))
    elements.append(t)
    doc.build(elements)

if __name__ == '__main__':
    testPdf()

此代码运行成功,因为该表在一个页面中,如果我将“SPAN”设置为“(0,0),(0,38)”,则错误为:

  

reportlab.platypus.doctemplate.LayoutError:可与包含
的单元格(0,0)一起流动       “1”(46.24 x 702)在第2页的“正常”(456.0 x 690.0 *)模板'后期'中太大了

如果我把它设置得更大,则错误将是:

Traceback (most recent call last):
  File "testpdf.py", line 26, in <module>
    testPdf()
  File "testpdf.py", line 23, in testPdf
    doc.build(elements)
  File "/usr/local/lib/python2.7/dist-packages/reportlab-2.5-py2.7-linux-x86_64.egg/reportlab/platypus/doctemplate.py", line 1117, in build
    BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)
  File "/usr/local/lib/python2.7/dist-packages/reportlab-2.5-py2.7-linux-x86_64.egg/reportlab/platypus/doctemplate.py", line 880, in build
    self.handle_flowable(flowables)
  File "/usr/local/lib/python2.7/dist-packages/reportlab-2.5-py2.7-linux-x86_64.egg/reportlab/platypus/doctemplate.py", line 763, in handle_flowable
    if frame.add(f, canv, trySplit=self.allowSplitting):
  File "/usr/local/lib/python2.7/dist-packages/reportlab-2.5-py2.7-linux-x86_64.egg/reportlab/platypus/frames.py", line 159, in _add
    w, h = flowable.wrap(aW, h)
  File "/usr/local/lib/python2.7/dist-packages/reportlab-2.5-py2.7-linux-x86_64.egg/reportlab/platypus/tables.py", line 1113, in wrap
    self._calc(availWidth, availHeight)
  File "/usr/local/lib/python2.7/dist-packages/reportlab-2.5-py2.7-linux-x86_64.egg/reportlab/platypus/tables.py", line 587, in _calc
    self._calc_height(availHeight,availWidth,W=W)
  File "/usr/local/lib/python2.7/dist-packages/reportlab-2.5-py2.7-linux-x86_64.egg/reportlab/platypus/tables.py", line 553, in _calc_height
    spanFixDim(H0,H,spanCons,lim=hmax)
  File "/usr/local/lib/python2.7/dist-packages/reportlab-2.5-py2.7-linux-x86_64.egg/reportlab/platypus/tables.py", line 205, in spanFixDim
    t = sum([V[x]+M.get(x,0) for x in xrange(x0,x1)])
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

我该如何处理?

1 个答案:

答案 0 :(得分:2)

你面临这个问题的原因正是戈登沃利上面评论过的。由于所实施的算法将与计算的高度和宽度混淆,因此无法跨页面自动跨越SPAN。

解决此问题的方法是使用行/列坐标手动格式化/设置每页的表格。遗憾的是,即使报告书中的回复也建议我们手动执行此操作。

我手动拆分我的表并分别设置它们,这在我看来是一个非常难看的方法。我稍后会寻找其他替代方案。

供参考:https://bitbucket.org/ntj/reportlab_imko_table