简体   繁体   中英

Adding pdf page for each record in dataframe using FPDF

I trying to iterate through pandas table and add PDF page for each row using FPDF library. The script only adds the very last record in the table and generates one page. I'm trying to figure out how to add a page for each record

import pandas as pd
from fpdf import FPDF
filename = 'alley.csv'
df= pd.read_csv(filename)

class PdfReport:
    def __init__(self, filename):
        self.filename = filename


    def generate(self, first_name,last_name, address_lane,city,zip_code, amount):
        pdf = FPDF(orientation='P', unit='pt', format='A4')
        pdf.add_page([])

        pdf.set_font(family="Times", size=24, style='B')
        pdf.cell(w=0, h=80, txt="Report Header", border=1, align="C", ln=1)
        pdf.cell(w=0, h=40, txt="Year: 2021 ", border=1,ln=1)
        pdf.cell(w=0, h=40, txt=first_name, border=1, ln=1)
        pdf.cell(w=0, h=40, txt=last_name, border=1, ln=1)
        pdf.cell(w=0, h=40, txt=address_lane, border=1, ln=1)
        pdf.cell(w=0, h=40, txt=city, border=1, ln=1)
        pdf.cell(w=0, h=40, txt=str(zip_code), border=1, ln=1)
        pdf.cell(w=0, h=40, txt=str(amount), border=1, ln=1)
        pdf.output(self.filename)

for ind in df.index:
    pdf_report= PdfReport(filename="Report1.pdf")
    pdf_report.generate(df['first_name'][ind], df['last_name'][ind], df['address_lane'][ind], df['city'][ind], df['zip_code'][ind],df['amount'][ind])

You can achieve that with a few edits made to your code.

import pandas as pd
from fpdf import FPDF
filename = './alley.csv'
df = pd.read_csv(filename)

class PdfReport(FPDF):
    def __init__(self, filename):
        FPDF.__init__(self) #initializes parent class
        self.filename = filename

    def generate(self, first_name,last_name, address_lane,city,zip_code, amount):
        pdf.add_page()
        pdf.set_font(family="Times", size=24, style='B')
        pdf.cell(w=0, h=80, txt="Report Header", border=1, align="C", ln=1)
        pdf.cell(w=0, h=40, txt="Year: 2021 ", border=1,ln=1)
        pdf.cell(w=0, h=40, txt=first_name, border=1, ln=1)
        pdf.cell(w=0, h=40, txt=last_name, border=1, ln=1)
        pdf.cell(w=0, h=40, txt=address_lane, border=1, ln=1)
        pdf.cell(w=0, h=40, txt=city, border=1, ln=1)
        pdf.cell(w=0, h=40, txt=str(zip_code), border=1, ln=1)
        pdf.cell(w=0, h=40, txt=str(amount), border=1, ln=1)

pdf = PdfReport(filename)
pdf.alias_nb_pages()

for ind in df.index:
    pdf.generate(df['first_name'][ind], df['last_name'][ind], df['address_lane'][ind], df['city'][ind], df['zip_code'][ind],df['amount'][ind])

pdf.output('PDF_TEST.pdf','F')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM