pyfpdf icon indicating copy to clipboard operation
pyfpdf copied to clipboard

How can I add page numbers to PDF document?

Open mphemming opened this issue 5 years ago • 5 comments

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?

mphemming avatar Nov 12 '20 06:11 mphemming

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)

cheikhnadiouf avatar Nov 22 '20 19:11 cheikhnadiouf

Thanks! I will try this

mphemming avatar Nov 22 '20 22:11 mphemming

FYI, this recipe is documented here in fpdf2 documentation: https://alexanderankin.github.io/pyfpdf/reference/footer.html

Lucas-C avatar Jan 09 '21 13:01 Lucas-C

is there no way to use function instead of class to handle it

joestar-hub avatar Nov 11 '22 12:11 joestar-hub

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

Lucas-C avatar Nov 11 '22 18:11 Lucas-C