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?
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?
Share Improve this question edited Feb 17 at 13:30 Lucas Cimon 2,0433 gold badges26 silver badges37 bronze badges asked Feb 17 at 5:49 smpa01smpa01 4,3463 gold badges17 silver badges29 bronze badges 01 Answer
Reset to default 2It 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.