pyfpdf
pyfpdf copied to clipboard
How can I add page numbers to PDF document?
I would like to add page numbers at the bottom of every page (except the first one which is a cover).
I was wondering if it's possible to do this using pyfpdf?
Override the add_page() method and the footer() method then add a condition parameter (isCover ?) for footer page as example below
from FPDF import *
class MyFPDFClass(FPDF):
def __init__(this, orientation='P',unit='mm',format='A4'):
self.isCover = False
# Override add_page methode
def add_page(this, same= True, orientation='', isCover= False):
FPDF.add_page(self, same= same, orientation=orientation)
# Override footer method
def footer(self):
# Page number with condition isCover
self.set_y(-15) # Position at 1.5 cm from bottom
if self.isCover == False:
self.cell(0, 10, 'Page ' + str(self.page_no) + ' | {nb}', 0, 0, 'C')
# Then call instruction with this instance line of your class :
# myfpdfclass.add_page(isCover = False)
# or
# myfpdfclass.add_page(isCover = True)
Thanks! I will try this
FYI, this recipe is documented here in fpdf2 documentation: https://alexanderankin.github.io/pyfpdf/reference/footer.html
is there no way to use function instead of class to handle it
With fpdf2, you can use the footer() method and the {{nb}} placeholder:
https://pyfpdf.github.io/fpdf2/Tutorial.html#tuto-2-header-footer-page-break-and-image