Create a PDF Report Generator in Python Using ReportLab

Create a PDF Report Generator in Python Using ReportLab

Create a PDF Report Generator in Python Using ReportLab

 

Generating professionally styled PDF reports is a common requirement for business applications, data dashboards, and automation workflows. Python’s ReportLab library makes this task incredibly powerful and flexible. In this article, we’ll walk through how to automatically generate PDF reports from user input or CSV files using ReportLab, complete with customized styling, tables, and layout techniques.

1. Installing ReportLab and Setting Up

ReportLab is a powerful PDF-generating library for Python. Begin by installing it using pip:

pip install reportlab

Once installed, you can import the relevant classes:

from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet

Now we can create a simple PDF file with a title and some static content to verify the setup:

doc = SimpleDocTemplate("sample_report.pdf", pagesize=A4)
elements = []
styles = getSampleStyleSheet()

# Add a title
title = Paragraph("Sample Report", styles['Title'])
elements.append(title)

doc.build(elements)

This will generate a simple PDF with a title. Let’s now look at how to populate the PDF with dynamic data.

2. Reading Input From a CSV File

Most real-world reports are based on structured data, often coming from CSVs. Let’s load user data from a CSV to inject into our PDF.

Here’s a sample data.csv file:

Name,Department,Salary
Alice Smith,Engineering,85000
Bob Jones,Marketing,60000
Charlie Brown,HR,50000

To read it:

import csv

def read_csv(file_path):
    with open(file_path, newline='') as csvfile:
        reader = csv.reader(csvfile)
        data = [row for row in reader]
    return data

This function returns a list of lists representing rows. Let’s feed this directly into our PDF table.

3. Creating a Styled PDF Table

The Table object in ReportLab’s platypus module lets us present structured data cleanly, with cell styling and borders.

data = read_csv("data.csv")
table = Table(data)

# Apply basic styling
table.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,0), colors.grey),
    ('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke),
    ('ALIGN', (0,0), (-1,-1), 'CENTER'),
    ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
    ('BOTTOMPADDING', (0,0), (-1,0), 12),
    ('GRID', (0,0), (-1,-1), 1, colors.black),
]))

elements.append(Spacer(1, 12))
elements.append(table)
doc.build(elements)

This produces a well-formatted PDF containing the employee data with headers. ReportLab enables developers to define precise styling for columns, rows, and individual cells.

4. Customizing Layout and Adding Metadata

You can control layout using ReportLab’s flowables like Spacer, Paragraph, and styles. Adding metadata such as headers or footers gives the report a polished feel.

from reportlab.pdfgen import canvas

def add_page_number(canvas, doc):
    page_num = canvas.getPageNumber()
    canvas.drawRightString(200*mm, 20*mm, f"Page {page_num}")

To use this, modify the build process:

doc.build(elements, onFirstPage=add_page_number, onLaterPages=add_page_number)

You can also add a cover page or summary paragraph dynamically based on user input or analysis results.

5. Automating the Report Generation Process

Once your base template is set up, it’s easy to turn this into a reusable script that runs on a schedule or from a CLI command. Here’s a function that encapsulates the entire flow:

def generate_pdf_report(csv_file, output_file):
    data = read_csv(csv_file)
    doc = SimpleDocTemplate(output_file, pagesize=A4)
    elements = []
    styles = getSampleStyleSheet()

    elements.append(Paragraph("Employee Salary Report", styles['Title']))
    elements.append(Spacer(1, 12))

    table = Table(data)
    table.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), colors.grey),
        ('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke),
        ('ALIGN', (0,0), (-1,-1), 'CENTER'),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('BOTTOMPADDING', (0,0), (-1,0), 12),
        ('GRID', (0,0), (-1,-1), 1, colors.black),
    ]))

    elements.append(table)
    doc.build(elements, onFirstPage=add_page_number, onLaterPages=add_page_number)

# Example usage
generate_pdf_report("data.csv", "employee_report.pdf")

This makes it easy to plug into a script that runs nightly, sends emails, or integrates with a web dashboard.

Conclusion

Using ReportLab, Python developers can automate fully styled PDF report generation with minimal effort. Whether you’re pulling in data from CSVs, databases, or APIs, this approach scales well across many reporting needs—from simple invoices to complex data summaries. For enhanced layout control, explore the canvas interface, charts, and barcodes offered by ReportLab’s extended capabilities.

By the end of this tutorial, you should be ready to build dynamic PDF generators that save time and improve the presentation quality of your output.

 

Useful links: