Search code examples
pythonfpdf

FPDF creates a pdf file with 1 extra page with every iteration


I've got a function from FPDF library to create pdf. Let's say, i have 4 orders and i need to create pdf for each of them, so i loop through them,

orders = [10, 11, 12, 13]
for o in orders: 
    generate_pdf(o)

Function generate_pdf:

from fpdf import FPDF
pdf = FPDF()
def generate_pdf(DokId):
    pdf.add_page()
    header = "Order #{}".format(DokId)
    
    pdf.set_font('Arial', 'B', 20)
    w = pdf.get_string_width(header) + 6
    pdf.set_x((210 - w) / 2)
    pdf.cell(w, 9, header, 0, 0, 'C')
    pdf.line(20, 18, 210-20, 18)
    pdf.output('{}.pdf'.format(DokId), 'F')
    return None

For first el in my list i've got file "10.pdf" with 1 page, for the next one - 2 pages, etc. How to avoid this case and create only one page for each order number in a loop?

Thanks in advance


Solution

  • I haven't used FPDF but I'm guessing the issue is that you are re-usig the same pdf object every time, and so after every call to add_page you add another page to the same document instead of a new one.

    Try adding

    pdf = FPDF()
    

    before your pdf.add_page() call.