拆分ReportLab Flowab

2024-10-02 10:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为ReportLab编写一个流式文件,它需要能够拆分。根据我对文档的理解,我需要定义一个函数split(self, aW, aH),它将流分解。但是,我遇到了以下我无法解决的错误。在

一个简单的流程:

class MPGrid (Flowable):
def __init__(self, height=1*cm, width=None):
    self.height = height
    self.width = None

def wrap(self, aW, aH):
    self.width = aW
    return (aW, self.height)

def split(self, aW, aH):
    if aH >= self.height:
        return [self]
    else:
        return [MPGrid(aH, aW), MPGrid(self.height - aH, None)]

def draw(self):
    if not self.width:
        from reportlab.platypus.doctemplate import LayoutError
        raise LayoutError('No Width Defined')

    c = self.canv
    c.saveState()
    c.rect(0, 0, self.width, self.height)
    c.restoreState()

在文档中使用并需要拆分时,会产生以下错误:

^{pr2}$

这个流动的高度应该是固定的,如果它对于可用的高度来说太大了,它将被拆分以消耗高度,然后在下一帧中提醒固定高度。在

我做错了什么导致了这个没用的错误?在


Tags: 文档selfnonereturnif高度def错误
1条回答
网友
1楼 · 发布于 2024-10-02 10:20:19

经过相当多的测试,我找到了一个答案。我仍然愿意接受更好的解决方案,如果有人有。在

之所以会发生这种情况,是因为调用了两次split,第二次调用的可用高度为零(或接近零),并且您尝试创建高度(接近)为零的可流动。解决方案是检查这种情况,在这种情况下不能拆分。在

为了使代码更加“完整”,下面的修订代码也有一些其他的小改动。在

class MPGrid (Flowable):
def __init__(self, height=None, width=None):
    self.height = height
    self.width = width

def wrap(self, aW, aH):
    if not self.width:  self.width = aW
    if not self.height: self.height = aH

    return (self.width, self.height)

def split(self, aW, aH):
    if aH >= self.height:
        return [self]
    else:
        # if not aH == 0.0: (https://www.python.org/dev/peps/pep-0485)
        if not abs(aH - 0.0) <= max(1e-09 * max(abs(aH), abs(0.0)), 0.0):
            return [MPGrid(aH), MPGrid(self.height - aH, None)]
        else:
            return []   # Flowable Not Splittable

def draw(self):
    if not self.width or not self.height:
        from reportlab.platypus.doctemplate import LayoutError
        raise LayoutError('Invalid Dimensions')

    c = self.canv
    c.saveState()
    c.rect(0, 0, self.width, self.height)
    c.restoreState()

相关问题 更多 >

    热门问题