Search code examples
pythonfpdf2

Fpdf header and background


I need to create a pdf with header, footer and background color. Tge following code is generating all 3, but it seems the footer is getting behind the pdf rect

from fpdf import FPDF

class PDF(FPDF):
    def header(self):
        self.set_font(family='Helvetica', size=8)
        self.cell(0, 10, 'test_header', align='L')

    def footer(self):
        self.set_y(-15)
        self.set_font(family='Helvetica', size=8)
        self.cell(0, 10, 'test_footer', align='L')

pdf = PDF()
pdf.add_page()
pdf.set_font("Times", size=12)

# BG
pdf.set_fill_color(r=249, g=247, b=242)
pdf.rect(h=pdf.h, w=pdf.w, x=0, y=0, style="F")

With the above only footer is visible but without it, both are visible.

How can I achieve the desired outcome?


Solution

  • It looks like the issue is that you're setting the background colour after you draw the page. The way you're doing it paints the background colour over everything, like what would happen if you painted a room without taking the posters off the wall.

    From a quick google search, FPDF doesn't have a method for modifying the background colour, so it might be best to squeeze the method into a component that will be going on all pages (in this case, i'll do it with the header).

    from fpdf import FPDF
    
    class PDF(FPDF):
        def header(self):
            # drawing the background
            self.set_fill_color(249, 247, 242)
            self.rect(0, 0, self.w, self.h, style="F")
    
            # then drawing the header
            self.set_font("Helvetica", size=8)
            self.cell(0, 10, "test_header", align="L")
        
        def footer(self):
            self.set_y(-15)
            self.set_font("Helvetica", size=8)
            self.cell(0, 10, "test_footer", align="L")
    
    pdf = PDF()
    pdf.add_page()
    pdf.set_font("Times", size=12)
    
    

    I know it's a rudimentary fix, but if you're using python to create a PDF then I'm assuming this isn't meant for production-level code, and this would be a strong enough bandaid fix.