使用 ReportLab 将页码和总页数正确添加到 PDF

Yot*_*lon 2 python pdf reportlab tableofcontents page-numbering

我正在尝试创建一个文档,该文档的页码格式为“Page x of y”。我已经尝试过 NumberedCanvas 方法(http://code.activestate.com/recipes/576832/以及论坛https://groups.google.com/forum/#!topic/reportlab-users/9RJWbrgrklI)但是与我的可点击目录 ( https://www.reportlab.com/snippets/13/ )冲突。

我从这篇文章http://two.pairlist.net/pipermail/reportlab-users/2002-May/000020.html 中了解到,使用表单是可能的,但是这方面的例子非常稀少且没有信息量。有没有人知道如何使用表单来实现这一点(或修复 NumberedCanvas 方法?)

Mar*_*tin 6

这个页面(http://www.blog.pythonlibrary.org/2013/08/12/reportlab-how-to-add-page-numbers/)解释了一个很好的方法。我做了一些更改以更好地利用继承。

它创建一个继承自 ReportLab Canvas 类的新类。

这是我修改后的代码:

from reportlab.lib.units import mm
from reportlab.pdfgen.canvas import Canvas


class NumberedPageCanvas(Canvas):
    """
    http://code.activestate.com/recipes/546511-page-x-of-y-with-reportlab/
    http://code.activestate.com/recipes/576832/
    http://www.blog.pythonlibrary.org/2013/08/12/reportlab-how-to-add-page-numbers/
    """

    def __init__(self, *args, **kwargs):
        """Constructor"""
        super().__init__(*args, **kwargs)
        self.pages = []

    def showPage(self):
        """
        On a page break, add information to the list
        """
        self.pages.append(dict(self.__dict__))
        self._startPage()

    def save(self):
        """
        Add the page number to each page (page x of y)
        """
        page_count = len(self.pages)

        for page in self.pages:
            self.__dict__.update(page)
            self.draw_page_number(page_count)
            super().showPage()

        super().save()

    def draw_page_number(self, page_count):
        """
        Add the page number
        """
        page = "Page %s of %s" % (self._pageNumber, page_count)
        self.setFont("Helvetica", 9)
        self.drawRightString(179 * mm, -280 * mm, page)
Run Code Online (Sandbox Code Playgroud)

要使用它只是改变CanvasNumberedCanvas创建一个新的文件时。当文件被保存时,数字被添加。