Search code examples
pythonreportlab

Format first row in ReportLab table


I'm building a very basic function to export a dataframe into a PDF table. At this point, I don't need any complex formatting as long as the data is readable. Looking up other code on the Internet, I'm nearly getting there, except that I can't see how I can get the header row of my table in bold.

import pandas as pd
from reportlab.platypus import *
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4

def df_to_pdf(data, pdf_file): # data is a DataFrame object
    table_data = [data.columns.values.tolist()] + data.values.tolist()
    grid = [('GRID', (0,0), (-1,-1), 0.25, colors.black)]
    pdf_table = Table(data=table_data, repeatRows=1, style=TableStyle(grid))
    doc = SimpleDocTemplate(pdf_file, pagesize=A4)
    element = []
    element.append(pdf_table)
    doc.build(element)

All I'd like is for the text in the first row (which will repeat on every page) to show in bold. Anything else I'm happy to keep simple.

Thanks!

R.


Solution

  • You're going to want to look at this on page 85

    grid = [('GRID', (0,0), (-1,-1), 0.25, colors.black), ('FONTNAME', (0,0), (0,-1), 'Courier-Bold')]
    

    Check page 28 for a list of available built in fonts.