CodeGym /Java Course /Python SELF EN /Basics of Creating PDF with Text for Automating Reporting...

Basics of Creating PDF with Text for Automating Reporting

Python SELF EN
Level 44 , Lesson 2
Available

1. Basics of Working with ReportLab

Working with Canvas

The main tool for creating PDF documents in ReportLab is the canvas class. It provides methods for adding text, lines, rectangles, and other graphical elements.

Creating a Simple PDF File with Text

Python

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4

# Create a new PDF file
pdf_file = canvas.Canvas("basic_report.pdf", pagesize=A4)
width, height = A4

# Add text
pdf_file.setFont("Helvetica", 12)  # Set font and size
pdf_file.drawString(100, height - 100, "Hello! This is a report created using ReportLab.")

# Save and close the PDF
pdf_file.save()

In this example, a simple PDF file is created with the text "Hello! This is a report created using ReportLab." on the first page.

2. Adding Text to a PDF

ReportLab allows you to customize text flexibly, including size, font, and color. This is important for creating structured reports, as headers, subheaders, and main text can look different.

Setting Font and Text Size

Use the setFont() method to set the font and text size. ReportLab supports standard fonts such as Helvetica, Times-Roman, and Courier.

Python

pdf_file.setFont("Helvetica-Bold", 16)  # Bold font
pdf_file.drawString(100, height - 50, "Sales Report")  # Title

Changing Text Color

ReportLab supports setting text color using the setFillColorRGB() method, which takes RGB values from 0 to 1.

Python

pdf_file.setFillColorRGB(0, 0, 1)  # Blue color
pdf_file.drawString(100, height - 150, "This text is blue.")

3. Working with Text Blocks and Multiline Text

If the text is long, you can format it as a block using drawString() and setting coordinates for each line. However, for automatic text wrapping, it is more convenient to use drawText() and TextObject.

Adding Multiline Text with TextObject

Python

text = """
Sales Report for 2023.
This report contains detailed information on sales, data analysis, and forecasts.
"""

# Create a text object
text_object = pdf_file.beginText(100, height - 200)
text_object.setFont("Helvetica", 12)
text_object.setFillColorRGB(0, 0, 0)

# Add text
for line in text.split("\n"):
    text_object.textLine(line)

pdf_file.drawText(text_object)

In this example, a TextObject is created that automatically wraps each line of text.

4. Creating Multi-Page Reports

Multi-page reports allow you to include more data and create a document structure that is easy to read. In ReportLab, the showPage() method is used to move to a new page.

Creating a Multi-Page PDF File

Python

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4

# Create PDF
pdf_file = canvas.Canvas("multi_page_report.pdf", pagesize=A4)
width, height = A4

# Page 1
pdf_file.setFont("Helvetica-Bold", 16)
pdf_file.drawString(100, height - 100, "Page 1: Introduction")
pdf_file.setFont("Helvetica", 12)
pdf_file.drawString(100, height - 130, "This is the first page of the report.")
pdf_file.showPage()  # Move to the next page

# Page 2
pdf_file.setFont("Helvetica-Bold", 16)
pdf_file.drawString(100, height - 100, "Page 2: Data")
pdf_file.setFont("Helvetica", 12)
pdf_file.drawString(100, height - 130, "This is the second page of the report.")

# Save and close the PDF
pdf_file.save()

In this example, a PDF with two pages is created, each with its own title and text. The showPage() method finishes the current page and starts a new one.

5. Adding Dynamic Data to PDF

To automate reporting, ReportLab allows you to add data dynamically, for example, from a list or dictionary. This is useful for creating reports with tables or data lists that may be regularly updated.

Adding Data from a List

Python

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4

data = [
    {"Month": "January", "Sales": 200},
    {"Month": "February", "Sales": 300},
    {"Month": "March", "Sales": 250},
]

pdf_file = canvas.Canvas("sales_report.pdf", pagesize=A4)
width, height = A4

# Title
pdf_file.setFont("Helvetica-Bold", 16)
pdf_file.drawString(100, height - 100, "Sales Report")

# Add data
pdf_file.setFont("Helvetica", 12)
y_position = height - 150
for item in data:
    line = f"{item['Month']}: Sales = {item['Sales']}"
    pdf_file.drawString(100, y_position, line)
    y_position -= 20

# Save the PDF
pdf_file.save()

This code creates a PDF file adding sales data for each month in separate lines.

6. Adding Images

Apart from text, PDF documents can include images and graphs. Let’s try adding an image:

Python

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

def create_pdf_with_image(file_path):
    c = canvas.Canvas(file_path, pagesize=letter)
    width, height = letter

    c.drawString(100, height - 100, "Here is your image:")
    # Path to your image
    image_path = "example_image.jpg"
    c.drawImage(image_path, 100, height - 300, width=200, height=150)

    c.showPage()
    c.save()

file_path = "image_example.pdf"
create_pdf_with_image(file_path)

Simple, right? Now we have a PDF with an image!

Now, knowing how to create a PDF with text and images, think about how you can apply this in real life. Let’s say you work in an analytics company and need to generate sales reports every month. Instead of preparing the document manually each time, you can write a script that automatically collects data and generates a PDF report. This not only saves your time but also improves accuracy and consistency of data in the report.

7. Adding Tables to PDF

Let’s take a small step away from simple text. What if we want to add data, for example, a list of products and their prices? Let's take a very simple example:

Python

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

items = [("Iron", 42.99), ("Kettle", 15.00), ("TV", 250.00)]

def create_pdf_with_table(file_path):
    c = canvas.Canvas(file_path, pagesize=letter)
    width, height = letter

    c.drawString(100, height - 100, "List of products and their price:")
    
    y = height - 150
    for item in items:
        c.drawString(100, y, f"{item[0]} - {item[1]:.2f} $")
        y -= 20

    c.showPage()
    c.save()

file_path = "table_example.pdf"
create_pdf_with_table(file_path)

Here we add a simple list of products with prices. Imagine the possibilities: you can create a complete table with data retrieved from another database, for example, from your favorite pandas DataFrame!

8. Using Templates for Automating Reports

One of the most powerful approaches to automating reporting is using templates. Essentially, you can create templates of documents with structure and design, and then populate them with data using your script.

Creating a Template Document

Create a main template that will contain static elements such as logos and fixed headers. Then automatically fill it with dynamic data, such as dates, charts, or lists. This can be arranged, for example, by using Jinja2 for template text and then generating the final PDF document.

For creating templates with ReportLab, you can use a combination of static and dynamic data. For example, a pre-prepared report background with company logos and constant elements, which are overlaid with dynamic content generated from application data.

1
Task
Python SELF EN, level 44, lesson 2
Locked
Creating a Simple PDF Document
Creating a Simple PDF Document
2
Task
Python SELF EN, level 44, lesson 2
Locked
Adding formatted text
Adding formatted text
3
Task
Python SELF EN, level 44, lesson 2
Locked
Creating a Multi-page PDF Document
Creating a Multi-page PDF Document
4
Task
Python SELF EN, level 44, lesson 2
Locked
Generating a Report with Data Table
Generating a Report with Data Table
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION