ReportLab中的动态间距器
我正在用Platypus自动生成一个PDF文件,这个文件的内容是动态的。
这意味着,文件底部的文本内容长度可能会有所不同。
不过,如果内容太长,有可能会出现分页的情况。这是因为我使用了一个“静态”的间隔器:
s = Spacer(width=0, height=23.5*cm)
因为我总是想让这个PDF文件只有一页,所以我需要动态设置这个间隔器的高度,让它填满页面剩下的空间。
那么,我该如何计算出页面上剩下的高度呢?
2 个回答
0
从我看到的情况来看,你是想要一个页脚,对吧?
那么你应该这样做:
def _laterPages(canvas, doc):
canvas.drawImage(os.path.join(settings.PROJECT_ROOT, 'templates/documents/pics/footer.png'), left_margin, bottom_margin - 0.5*cm, frame_width, 0.5*cm)
doc = BaseDocTemplate(filename,showBoundary=False)
doc.multiBuild(flowble elements, _firstPage, _laterPages)
3
我在reportlab库里稍微研究了一下,发现了以下内容:
基本上,我决定使用一个框架来放置要打印的内容。f._aH可以返回这个框架的高度(我们也可以手动计算这个高度)。然后,我们通过wrap方法获取其他两个内容的高度,减去它们的高度后,就得到了剩余的高度,这个剩余的高度就是Spacer的高度。
elements.append(Flowable1)
elements.append(Flowable2)
c = Canvas(path)
f = Frame(fx, fy,fw,fh,showBoundary=0)
# compute the available height for the spacer
sheight = f._aH - (Flowable1.wrap(f._aW,f._aH)[1] + Flowable2.wrap(f._aW,f._aH)[1])
# create spacer
s = Spacer(width=0, height=sheight)
# insert the spacer between the two flowables
elements.insert(1,s)
# create a frame from the list of elements
f.addFromList(elements,c)
c.save()
测试过了,效果很好。