Search code examples
pythonfpdf

Python FPDF rendering issue


I'm looking for some assistance with this code below. When I run the "title.py" I get the expected results on a PDF. However, when I import that class into main.py, I get a blank PDF page. I am not sure what I am doing wrong. Any help would be appreciated.

title.py:

from fpdf import FPDF


class TitlePage(FPDF):
    def __init__(self):
        super().__init__()
        self.price_book_title()

    def price_book_title(self):
        self.add_page()
        self.set_font('arial', 'B', 18)
        self.set_text_color(r=11, g=74, b=122)
        title = 'TEST PDF NAME'
        title_w = self.get_string_width(title)
        self.set_xy(x=((self.w - title_w) / 2), y=(self.h / 5))
        self.cell(title_w, txt=title, align='C')


temp = TitlePage()
temp.price_book_title()

temp.output('Title Page Test.pdf')

main.py

from fpdf import FPDF
from title import TitlePage

pdf = FPDF()
title_page = TitlePage()

title_page.price_book_title()

pdf.output('TEST.pdf')

Solution

  • I have had a quick look at the PyFPDF docs here, and I have found a snippet which looks similar to yours - I think you should change your main.py file as follows:

    from title import TitlePage
    
    title_page = TitlePage()
    title_page.price_book_title()
    title_page.output('TEST.pdf')
    

    Like in the docs snippet, your class extends the FPDF class, so you should be able to just call the output method on it - the reason why you're getting a blank page is that you're saving the empty document created with pdf = FPDF() rather than your class created with title_page = TitlePage().