DEV Community

qing
qing

Posted on

Build a PDF Report Generator with Python

Build a PDF Report Generator with Python

Automate Your Reporting Workflow with a Python PDF Generator

As developers, we often find ourselves generating reports from data, whether it's a simple status update or a detailed analysis of our application's performance. While manual report generation can be tedious and time-consuming, it's a necessary evil in many cases. However, what if you could automate this process and have a professionally formatted PDF report in seconds? That's exactly what we'll explore in this post: building a PDF report generator using Python.

Setting Up the Project

Before we dive into the code, let's set up the project structure. We'll use a simple directory structure with two main files: main.py for the report generator and utils.py for utility functions that we'll use later on. Create a new directory for your project and navigate to it in your terminal or command prompt. Then, create the two files:

mkdir pdf_report_generator
cd pdf_report_generator
touch main.py
touch utils.py
Enter fullscreen mode Exit fullscreen mode

Installing Required Libraries

To generate PDF reports, we'll use the fpdf library, which is a lightweight and easy-to-use Python wrapper for the FPDF library. Install it using pip:

pip install fpdf
Enter fullscreen mode Exit fullscreen mode

Creating the Report Generator

Now that we have our project set up and the required library installed, let's create the report generator. In the main.py file, add the following code:

from fpdf import FPDF
from utils import get_report_data

def generate_report():
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size = 15)
    pdf.cell(200, 10, txt = "Report", ln = True, align = 'C')

    report_data = get_report_data()
    for item in report_data:
        pdf.cell(200, 10, txt = item['name'] + ": " + item['value'], ln = True, align = 'L')

    pdf.output("report.pdf")

if __name__ == '__main__':
    generate_report()
Enter fullscreen mode Exit fullscreen mode

In this code, we create a new FPDF object and add a page. We then set the font and cell height, and add a header cell with the text "Report". Next, we call the get_report_data function (which we'll create in the utils.py file) to retrieve the report data, and for each item in the report data, we add a new cell with the item's name and value.

Retrieving Report Data

Now that we have the report generator set up, let's create the get_report_data function in the utils.py file:

def get_report_data():
    # Simulating report data from a database or API
    report_data = [
        {'name': 'CPU Usage', 'value': '50%'},
        {'name': 'Memory Usage', 'value': '60%'},
        {'name': 'Disk Usage', 'value': '80%'}
    ]
    return report_data
Enter fullscreen mode Exit fullscreen mode

In this code, we simulate report data from a database or API by creating a list of dictionaries. Each dictionary represents an item in the report data, with keys for the item's name and value.

Customizing the Report

So far, our report generator is quite basic. Let's add some customization to make it more useful. We can add a section header, a footer with the report date, and some styling to make the report more readable.

def generate_report():
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size = 15)
    pdf.cell(200, 10, txt = "Report", ln = True, align = 'C')

    # Add a section header
    pdf.set_font("Arial", size = 12)
    pdf.cell(200, 10, txt = "System Resources", ln = True, align = 'L')
    pdf.ln(10)

    report_data = get_report_data()
    for item in report_data:
        pdf.cell(200, 10, txt = item['name'] + ": " + item['value'], ln = True, align = 'L')

    # Add a footer with the report date
    pdf.set_font("Arial", size = 9)
    pdf.cell(200, 10, txt = "Report generated on: " + str(datetime.date.today()), ln = True, align = 'L')

    pdf.output("report.pdf")
Enter fullscreen mode Exit fullscreen mode

Now that we have a more customized report generator, let's add some styling to make the report more readable.

def generate_report():
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size = 15)
    pdf.cell(200, 10, txt = "Report", ln = True, align = 'C')

    # Add a section header
    pdf.set_font("Arial", size = 12)
    pdf.cell(200, 10, txt = "System Resources", ln = True, align = 'L')
    pdf.ln(10)

    pdf.set_font("Arial", size = 10)
    report_data = get_report_data()
    for item in report_data:
        if item['name'] == 'CPU Usage':
            pdf.set_text_color(255, 0, 0)  # Red color for CPU usage
        elif item['name'] == 'Memory Usage':
            pdf.set_text_color(0, 255, 0)  # Green color for memory usage
        elif item['name'] == 'Disk Usage':
            pdf.set_text_color(0, 0, 255)  # Blue color for disk usage
        pdf.cell(200, 10, txt = item['name'] + ": " + item['value'], ln = True, align = 'L')
        pdf.set_text_color(0, 0, 0)  # Reset text color to black

    # Add a footer with the report date
    pdf.set_font("Arial", size = 9)
    pdf.cell(200, 10, txt = "Report generated on: " + str(datetime.date.today()), ln = True, align = 'L')

    pdf.output("report.pdf")
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this post, we've built a PDF report generator using Python and the fpdf library. We've customized the report generator to add a section header, a footer with the report date, and some styling to make the report more readable. With this report generator, you can automate your reporting workflow and have a professionally formatted PDF report in seconds. Whether you're generating reports from data or creating custom documents, this report generator is a versatile tool that you can use TODAY. So go ahead, give it a try, and see how it can simplify your reporting workflow!


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*

Top comments (0)