【问题标题】:Footer only on last data page in Reportlab仅在 Reportlab 中的最后一个数据页上的页脚
【发布时间】:2013-06-12 09:39:37
【问题描述】:

我正在处理发票,我只想在最后一页(也可以是第一页)添加页脚。

由于表格的数据是动态的,我无法计算页数。

现在我正在使用 2 个页面模板,首页(带有 2 个框架和页脚 1)和下一页(带有 1 个框架和页脚 2)。这在数据填充两页时有效,但当表格仅填充一页或多于 2 页时,它不再有效。

我通过以下方式定义了页脚:

    footerFrame = Frame(x1=35*mm, y1=20*mm, width=175*mm, height=15*mm)
    footerStory = [ Paragraph("Have a nice day.", styles["fancy"]) ]

    def footer2(canvas,document):
        canvas.saveState()
        footerFrame.addFromList(footerStory, canvas)
        canvas.restoreState()

是否有更灵活的方式来定义页脚,使其仅显示在表格结束的页面上?

提前致谢。

【问题讨论】:

    标签: footer reportlab


    【解决方案1】:

    通过覆盖 ReportLabs 画布类,您可以跟踪页面(当然,我已经使用其他不涉及可流动的报告完成了它,但我相信您仍然可以让它工作!)。

    由于您使用的是可流动的(段落),您需要知道每一代新的 PDF 将有多少页(长度是动态部分)。我不是 100% 肯定的,但我认为 ReportLab 的 flowable 仍然调用画布的“showPage()”方法。因此,您可以执行以下操作:

    在伪代码/部分python中,我推荐以下(未经测试):

    class MyFooterCanvas(canvas.Canvas):
        def __init__(self, *args, **kwargs):
            ## Subclass the ReportLab canvas class.  
            canvas.Canvas.__init__(self, *args, **kwargs)
            ## Create an empty list to store the saved pages so you can keep track of them.
            self._savedPages = []
    
        def showPage(self):
            """Override the showPage method"""
    
            ## We are writing our own showPage() method here, so we can keep track of 
            ## what page we are on.
            self._savedPages.append(self)
            ## Start a new page.
            self._startPage()
    
        def drawFooter(self):
            """Draws the footer to the page.  You can have it do whatever you want here"""
            self.drawString(50, 50, "This is my footer, yay me - footer freedom")
    
        def save(self):
            """Saves the entire PDF in one go, a bit costly to do it this way,
               but certainly one way to get a footer."""
            numPages = len(self._savedPages)
    
            for pages in self._savedPages:
                ## Finds the last page and when it 'hits', it will call the self.drawFooter() method.
                if pages == self._savedPages[-1]:
                    self.drawFooter()
                else:
                    ## If it's not the last page, explicitly pass over it.  Just being thorough here.
                    pass
    
            ## And... continue doing whatever canvas.Canvas() normally does when it saves.
            canvas.Canvas.save(self)
    

    再次这是未经测试的,但我认为这会给你你想要的行为。试试看,如果你卡住了,请告诉我,如果需要,我可以解决其中的一些问题,但我对其他不可流动的东西也做过同样的方法,过去它对我有用。

    【讨论】:

    • 谢谢,我试试看告诉你。
    • 你的例子也对我有用,谢谢。在 init__ 之后的第 2 行中,括号中有一个小错字。
    • @Helga,很高兴它对你有用!感谢您发现那个小错字......现在应该修复它。另外,如果您愿意将此问题标记为正确的问题!我喜欢获得“分数”:P 一次自我推销一个 SO 问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多