使用 ReportLab 将页码和总页数正确添加到 PDF [英] Properly add page numbers and total number of pages to PDF using ReportLab
问题描述
我正在尝试创建一个页码格式为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/).
I am trying to create a document that has page numbering of the format "Page x of y". I have tried the NumberedCanvas approach (http://code.activestate.com/recipes/576832/ and also from the forums https://groups.google.com/forum/#!topic/reportlab-users/9RJWbrgrklI) but that conflicts with my clickable Table of Contents (https://www.reportlab.com/snippets/13/).
我从这篇文章中了解到 http://two.pairlist.net/pipermail/reportlab-users/2002-May/000020.html 可以使用表单,但是这方面的示例非常稀少且没有信息量.有没有人知道如何使用表单来实现这一点(或修复 NumberedCanvas 方法?)
I understood from this post http://two.pairlist.net/pipermail/reportlab-users/2002-May/000020.html that it may be possible using forms, but examples on this are very scarce and uninformative. Does anybody have any idea on how this can be implemented using forms (or fixing the NumberedCanvas approach?)
推荐答案
此页面 (http://www.blog.pythonlibrary.org/2013/08/12/reportlab-how-to-add-page-numbers/) 解释了一个很好的方法来做到这一点.我做了一些更改以更好地利用继承.
This page (http://www.blog.pythonlibrary.org/2013/08/12/reportlab-how-to-add-page-numbers/) explains a good way to do it. I made some changes to make better use of inheritance.
它创建了一个继承自 ReportLab Canvas 类的新类.
It creates a new Class that inherits from ReportLab Canvas class.
这是我修改后的代码:
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)
要使用它,只需在创建新文件时将 Canvas
更改为 NumberedCanvas
.保存文件时,会添加数字.
To use it just change Canvas
for NumberedCanvas
when creating a new file. When the file is saved the numbers are added.
这篇关于使用 ReportLab 将页码和总页数正确添加到 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!