To add a footer with the page number on each page using Python's ReportLab library, you can subclass BaseDocTemplate and override the afterDrawPage method. This method is called after each page is rendered, allowing you to draw custom content, such as a footer with the current page number.
Here's a step-by-step explanation and a complete example:
Step-by-Step Explanation:
- Import Necessary Modules: You'll need modules from ReportLab for creating the document, adding content, and drawing on the canvas.
- Create a Custom Document Class: Subclass
BaseDocTemplate and override the afterDrawPage method. In this method:
- Use the canvas to draw text (e.g., "Page X").
- Access the current page number via the
doc.page attribute.
- Position the text at the bottom of the page using coordinates (e.g., near the bottom-left corner).
- Build the Document: Create an instance of your custom document class, add content (e.g., paragraphs), and use the
build method to generate the PDF.
- Handle Page Layout: Use the canvas's drawing methods to place the footer at a specific position. You can adjust the font, size, and position as needed.
- Generate Multi-Page Content: To demonstrate footers on multiple pages, add enough content to span more than one page.
Complete Example Code:
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, BaseDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch # For easier unit handling
class FooterDocTemplate(BaseDocTemplate):
def afterDrawPage(self, canvas, doc):
"""
This method is called after each page is drawn.
We use it to add a footer with the page number.
"""
canvas.saveState() # Save the current canvas state
canvas.setFont("Helvetica", 9) # Set font and size for the footer
page_number = doc.page # Get the current page number
pagesize = letter # Get the page size (width, height)
footer_text = f"Page {page_number}" # Format the footer text
# Draw the footer text at the bottom of the page (e.g., 0.5 inches from the bottom, left-aligned)
canvas.drawString(0.5 * inch, 0.5 * inch, footer_text)
canvas.restoreState() # Restore the canvas state
# Main script to build the PDF
def generate_pdf(filename):
doc = FooterDocTemplate(filename, pagesize=letter) # Create the custom document
styles = getSampleStyleSheet() # Get sample styles for paragraphs
# Create some sample content to span multiple pages
content = []
for i in range(1, 50): # This will create multiple pages
content.append(Paragraph(f"This is paragraph {i} on the document.", styles['Normal']))
content.append(Spacer(1, 12)) # Add some space between paragraphs
doc.build(content) # Build the PDF with the content
# Run the function
if __name__ == "__main__":
generate_pdf("output_with_footer.pdf")
print("PDF generated successfully with footers!")
How This Works:
- Custom Class (
FooterDocTemplate): This inherits from BaseDocTemplate. The afterDrawPage method is overridden to draw the footer. It uses canvas.drawString to place the text "Page X" at the bottom of the page.
doc.page gives the current page number (e.g., 1, 2, 3, etc.).
- The position
(0.5 * inch, 0.5 * inch) places the text 0.5 inches from the left and 0.5 inches from the bottom of the page. You can adjust this as needed (e.g., to center the text).
- Content Generation: The script creates a list of paragraphs using
Paragraph flowables. Adding Spacer ensures the content flows across multiple pages.
- Building the PDF: The
doc.build(content) method processes the content and generates the PDF, calling afterDrawPage for each page.
Output:
- When you run this script, it will create a PDF file named
output_with_footer.pdf.
- Each page will have a footer at the bottom-left corner (e.g., "Page 1", "Page 2", etc.).
Customization Tips:
- Positioning the Footer:
- To center the footer horizontally, calculate the x-position like this:
text_width = canvas.stringWidth(footer_text, "Helvetica", 9)
x_position = (pagesize[0] - text_width) / 2 # Center horizontally
canvas.drawString(x_position, 0.5 * inch, footer_text)
- Font and Style: Change the font with
canvas.setFont("FontName", size). You can register custom fonts if needed.
- Adding More to the Footer: If you want to include additional text (e.g., "Page X of Y"), it's more complex because the total number of pages isn't known until the document is built. You might need to use a two-pass approach or ReportLab's
PageXofY flowable.
- Error Handling: Ensure you have ReportLab installed (
pip install reportlab). If you encounter issues, check the file path and permissions for writing the PDF.
This approach is simple and effective for most use cases. If you need more advanced features (e.g., headers, images in the footer), let me know!