Wrap Table Column Name with FPDF

Viewed 213

Saw different thread but not Python so I will be asking here.

Given following dataframe such as:

df = pd.DataFrame(np.random.randint(0,100,size=(8, 4)), columns=list('ABCD'))
df.columns = ['history_summary_number_1', 'history_summary_number_2', 'history_summary_number_3', 'history_summary_number_4']

I want to extract that df as table in a PDF file and wrap headers in a way where it does not spill over table borders.

In order to do so I have the following code:

def output_df_to_pdf(pdf, df):
    # Set the width and height of cell
    table_cell_width = 13
    table_cell_height = 5
    # Select a font as Helvetica, bold, 5
    pdf.set_font('Helvetica', 'B', 5)
    
    # Loop over to print column names
    cols = df.columns
    for col in cols:
        pdf.cell(table_cell_width, table_cell_height, col, align='C', border=1)
    # Line break
    pdf.ln(table_cell_height)
    # Select a font as Helvetica, regular, 4
    pdf.set_font('Helvetica', '', 4)
    # Loop over to print each data in the table
    for row in df.itertuples():
        for col in cols:
            value = str(getattr(row, col))
            pdf.cell(table_cell_width, table_cell_height, value, align='C', border=1)
        pdf.ln(table_cell_height)

Which gives:

pdf = FPDF()
pdf.add_page()
output_df_to_pdf(pdf, df)
pdf.output('test.pdf', 'F')

I tried to replace for the header part pdf.cell to pdf.multi_cell without success:

Multi cell

Was wondering if I was missing something using multi cell or if I need to change my approach altogether.

Thank you!

0 Answers
Related