Tue, 04 Apr 2006

using reportlab forms for page numbers

I've been doing alot of work with reportlab recently and a problem that I ran into was creating a pdf with page numbers in the form of page x of y. After some digging around I found some posts about people talking about using forms to store the page number and referencing those on each page. However I couldn't find a working example and since I didn't have any experience with reportlab forms it took a while to finally get it working how I wanted. Anyways, I thought I'd post my findings as they might be useful to someone else trying to do the same.

Basicly I started by using an example I found in the reportlab user mailing lists to create a flowable which I append to the document at the very end. This creates the form and draws the last page number.
class lastPageNumberFlowable(Flowable):


def __init__(self, xoffset = 0, yoffset = 0):
Flowable.__init__(self)
self._xoffset = xoffset
self._yoffset = yoffset

def draw(self):
canvas = self.canv
if not canvas.hasForm("lastPageNumber"):
canvas.beginForm('lastPageNumber')
canvas.setFont('Times-Roman',9)
canvas.drawString(PAGE_WIDTH - 2.2 * cm, 2 * cm, "%d" % (doc.page, ))
canvas.endForm()

Story.append(lastPageNumberFlowable())

doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)


Then in the myLaterPages function I call doForm which writes the last page number on the page, and I also write the Page x of string just before it.


def myLaterPages(canvas, doc):
canvas.saveState()
canvas.doForm('lastPageNumber')
canvas.setFont('Times-Roman',9)
canvas.drawRightString(PAGE_WIDTH - 2.3 * cm, 2 * cm, "Page %d of" % (doc.page, ))
canvas.restoreState()


And I include the same thing in the myFirstPage function as well. This produces a Page x of y string on each page which also formats well enough due to the way the strings get drawn left and right of a specific point (it expands properly with more than single digit page numbers).

I've created a working example which you can download. Run it and provide a filename and it will create a pdf with page x of y page numbers.
reportlab_pageof_example.py

posted at: 12:59 | path: /general | permanent link to this entry


2019-Jun
2019-May
2018-Dec
2018-Jan
2017-Aug
2017-Jun
2017-May
2016-Nov
2015-Dec
2015-Nov
2015-Oct
2015-Jul
2015-Jun
2014-Dec
2012-Oct
2012-Sep
2012-Jun
2012-Feb
2012-Jan
2011-Dec
2011-Sep
2011-Aug
2011-May
2011-Feb
2010-Jun
2010-Apr
2010-Jan
2009-Sep
2009-Jul
2009-May
2009-Jan
2008-Oct
2008-Sep
2008-Jun
2008-May
2008-Jan
2007-Nov
2007-Oct
2007-Aug
2007-Jun
2007-May
2007-Mar
2007-Feb
2007-Jan
2006-Nov
2006-Oct
2006-Sep
2006-Aug
2006-Jun
2006-Apr
2006-Jan
2005-Dec
2005-Nov
2005-Oct
2005-Sep
2005-Aug
2005-Jul
2005-Jun
2005-May
2005-Apr
2005-Mar
2005-Feb
2005-Jan
2004-Dec
2004-Nov
2004-Oct
2004-Sep
2004-Aug
2004-Jul
2004-Jun
2004-May

Powered by PyBlosxom | RSS 2.0