USING IRONPDF FOR PYTHON

How to Generate A PDF Report in Python

Updated October 7, 2024
Share:

Generating PDF file reports is a common requirement for data analysis and data scientists. IronPDF is a versatile library that enables the creation of PDF table files in Python code applications similar to the FPDF library in PHP. This tutorial will guide you through using IronPDF to create and write reports in PDF from HTML templates or URLs, which can be time-consuming if not done correctly.

IronPDF: Python PDF Library

IronPDF is a comprehensive library designed for Python applications to create PDFs, edit, and extract content from PDF files. It's a powerful tool that caters to the needs of software engineers who often face the challenge of generating final results for PDF documents from various data sources or templates. With IronPDF, users can effortlessly transform HTML content or URLs into PDF files, manipulate PDF content, and integrate these capabilities into Python code projects, making it an essential library for any Python developer dealing with PDF generation and manipulation tasks.

IronPDF also allows you to build interactive forms, split and combine PDF files, extract text and images from PDF files, search for certain words within a PDF file, rasterize PDF pages to images, as well as print PDF files.

Prerequisites

The first step is to make sure you meet the following prerequisites:

  1. Python 3.7 or higher installed on your system.
  2. .NET 6.0 runtime installed since the IronPDF library relies on .NET 6.0 as its underlying technology.

You can install the .NET 6.0 runtime from the official .NET download page.

Installation

To use IronPDF, you need to install the package via pip:

pip install ironpdf

How to Generate A PDF Report in Python, Figure 1: Install IronPDF Install IronPDF

IronPDF will automatically download additional dependencies upon its first run.

Creating a Simple PDF Document

Here's a sample code example to generate a simple PDF document using an HTML template:

from ironpdf import *

renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
pdf.SaveAs("hello_world.pdf")
PYTHON

This code snippet converts an HTML string into a PDF file and saves it in the same folder as your Python script.

Generating PDF from URL

IronPDF can also create a PDF from a web page URL with the following sample code:

from ironpdf import *

renderer = ChromePdfRenderer()
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/python/")
pdf.SaveAs("website_snapshot.pdf")
PYTHON

Generating PDF Reports with Data Frames

Creating professional-looking PDF reports is straightforward with IronPDF and Python. Here's how you can generate an enhanced report using detailed data frames and customized HTML styling:

Step 1: Importing Libraries

First, you need to import the required libraries. ChromePdfRenderer from IronPDF is essential for the PDF generation process. This library enables the conversion of HTML content to PDF documents. Additionally, import pandas, a powerful data manipulation library, to create and manage data frames. Pandas will be used to structure your report's data in a tabular format.

from ironpdf import ChromePdfRenderer
import pandas as pd
PYTHON

Step 2: License Key Configuration

Activating IronPDF requires setting your license key. This step is crucial as it unlocks all features of IronPDF, allowing you to generate PDFs without any watermarks or limitations. It's a simple yet vital step for professional use of the library.

License.LicenseKey = "Your-License-Key"
PYTHON

Step 3: Creating a Data Frame

Here, you'll create a data frame using Pandas. This data frame acts as the data source for your report. The example provided includes detailed employee information, demonstrating Pandas' capability in handling and structuring complex data sets. The data frame can be customized based on the specifics of the report you intend to create.

data = {
  'Employee ID': [101, 102, 103, 104],
  'Name': ['John Doe', 'Alice Smith', 'Bob Johnson', 'Emily Davis'],
  'Age': [28, 34, 45, 29],
  'Department': ['Sales', 'HR', 'IT', 'Marketing'],
  'City': ['New York', 'London', 'San Francisco', 'Berlin']
}
df = pd.DataFrame(data)
PYTHON

Step 4: Designing the HTML Template

In this step, you'll design an HTML template with CSS styling. This template defines the visual presentation of your PDF report. CSS styling enhances the visual appeal and readability of the data presented in the report. The dynamic insertion of the data frame into this HTML template is handled through Python's string formatting.

# HTML styling for the PDF report
html_style = """
<html>
<head>
<style>
  table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
    padding: 5px;
    text-align: left;
  }
  th {
    background-color: #f2f2f2;
  }
</style>
</head>
<body>
  <h2>Company Employee Report</h2>
  {table}
</body>
</html>
"""

# Replace {table} with the HTML representation of the data frame
html_content = html_style.format(table=df.to_html(index=False, border=0))
PYTHON

Step 5: Rendering and Saving the PDF

Finally, use IronPDF's ChromePdfRenderer to convert the HTML content into a PDF document. The RenderHtmlAsPdf method processes the HTML and CSS, converting it into a PDF file. The SaveAs function is then used to save this file, resulting in a well-formatted, visually appealing PDF report. This step encapsulates the conversion process, combining the data and template into a final document.

# Render the HTML string to a PDF document
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(html_content)
pdf.SaveAs("enhanced_employee_report.pdf")
PYTHON

Output

Here is the output report in PDF:

How to Generate A PDF Report in Python, Figure 2: Company Employee Report Company Employee Report

Creating a Simple PDF Document

Here's a sample code to generate a simple PDF document using an HTML template:

from ironpdf import *

renderer = ChromePdfRenderer() 
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>") 
pdf.SaveAs("hello_world.pdf")
PYTHON

This code snippet converts an HTML string into a PDF file and saves it in the same folder as your Python script.

Generating PDF from URL

IronPDF can also create a PDF from a web page URL with the following sample code:

from ironpdf import *

renderer = ChromePdfRenderer()
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/python/")
pdf.SaveAs("website_snapshot.pdf")
PYTHON

This will save a PDF snapshot of the specified webpage.

Conclusion

IronPDF is a powerful tool for Python developers and data scientists to generate PDF reports. By following this guide, you can easily integrate PDF generation into your Python projects, whether you're creating PDFs from HTML templates, URLs, or data frames. Remember to explore IronPDF's extensive documentation and examples to leverage its full capabilities for your PDF tasks such as adding a pie chart.

Keep experimenting with different features and options IronPDF provides to create PDF reports that meet your needs. With the right approach, what seems like a time-consuming task can become an efficient and automated part of your workflow.

IronPDF offers a free trial, allowing users to fully explore its features before committing to a purchase. Additionally, it's free for development purposes, providing a cost-effective solution for developers during the development phase. For commercial deployment, licensing for IronPDF starts at $749, catering to professional and enterprise-level needs.

< PREVIOUS
How to Add Digital Signature in Python
NEXT >
Best PDF Reader for Python (Free & Paid Tools)

Ready to get started? Version: 2024.11.1 just released

Free pip Install View Licenses >