PDF Report created with ReportLab library
ReportLab is a powerful PDF generation library that allows developers to create complex reports with a high degree of customization. This blog post will guide you through the different functionalities of the ReportLab library.
Introduction about ReportLab
ReportLab is a robust, open-source library that facilitates the rapid creation of richly formatted PDF reports in Python. It provides a flexible and versatile platform for generating and customizing PDFs with a wide range of features. The library was created around 2010 and has been actively maintained and updated since then, with the latest version being released in February 2024.
In this guide, we will introduce a Python class that encapsulates various functionalities of the ReportLab library. Each functionality will be implemented as a separate method within the class.
from reportlab.lib.pagesizes import letter from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.platypus import SimpleDocTemplate, Paragraph, Image, PageTemplate, Frame, TableOfContents from reportlab.graphics.shapes import Drawing from reportlab.graphics.charts.barcharts import VerticalBarChart from reportlab.pdfgen import canvas from pdfrw import PdfReader, PdfWriter class ReportLabGuide: def __init__(self): pass def create_headers(self): pass def format_paragraphs(self): pass def insert_graphics(self): pass def insert_charts(self): pass def set_page_headers_footers(self): pass def set_watermarks(self): pass def generate_table_of_contents(self): pass def add_pdfs(self): pass |
Headers in Different Sizes
Headers are crucial for structuring your document. ReportLab allows you to create headers in various sizes using the ParagraphStyle class. You can define a style and specify the font size to create headers of different sizes.
def create_headers(self): # Define styles for different header sizes header_style = ParagraphStyle('HeaderStyle', fontSize=18, spaceAfter=12) subheader_style = ParagraphStyle('SubheaderStyle', fontSize=14, spaceAfter=6) # Create headers header = Paragraph('This is a header', header_style) subheader = Paragraph('This is a subheader', subheader_style) # Add headers to the story self.story.append(header) self.story.append(subheader) |
This snippet outlines the process of creating headers of different sizes. We first define styles for our headers and subheaders. We then create Paragraph objects for each of our headers, specifying the text and the style. Finally, we add our headers to the story.
Paragraphs and Text Formatting
ReportLab provides extensive options for formatting text within paragraphs. You can set the font, font size, and apply bold, italic, underline, and hyperlink styles.
def format_paragraphs(self): # Get a sample style sheet styles = getSampleStyleSheet() # Create a paragraph with bold text bold_text = Paragraph("<b>This is bold text</b>", styles['BodyText']) # Create a paragraph with italic text italic_text = Paragraph("<i>This is italic text</i>", styles['BodyText']) # Create a paragraph with underlined text underlined_text = Paragraph("<u>This is underlined text</u>", styles['BodyText']) # Create a paragraph with a hyperlink hyperlink_text = Paragraph("<a href='http://www.google.com'>This is a hyperlink</a>", styles['BodyText']) # Add paragraphs to the story self.story.extend([bold_text, italic_text, underlined_text, hyperlink_text]) |
The above code demonstrates how to format text within paragraphs. We first get a sample style sheet. We then create Paragraph objects for each of our formatted texts, specifying the text and the style. The text is formatted using HTML-like tags. Finally, we add our paragraphs to the story.
Inserting Graphics and Pictures
ReportLab supports the insertion of graphics and pictures into your PDF documents. You can use the Image class to add images
def insert_graphics(self): # Create an image object img = Image('path_to_image.jpg', width=200, height=200) # Add the image to the story self.story.append(img) |
The code above illustrates how to insert graphics into your PDF documents. We first create an Image object for our image, specifying the path to the image and the desired width and height. Finally, we add our image to the story.
Inserting Different Types of Charts
ReportLab includes a powerful charting module that supports various types of charts, including line charts, pie charts, and bar charts.
def insert_charts(self): # Create a drawing object drawing = Drawing(400, 200) # Create a bar chart chart = VerticalBarChart() chart.data = [[1, 2, 3, 4, 5]] chart.x = 50 chart.y = 50 chart.height = 125 chart.width = 300 # Add the chart to the drawing drawing.add(chart) # Add the drawing to the story self.story.append(drawing) |
The code segment above shows how to insert different types of charts into your PDF documents. We first create a Drawing object and a VerticalBarChart object for our chart. We specify the data for the chart and its position and size. We add the chart to the drawing and the drawing to our story.
Setting Page Headers and Footers
You can add headers and footers to your pages using the PageTemplate and Frame classes. Headers and footers can include text and logos.
def set_page_headers_footers(self): # Define a function to create a header def header(canvas, doc): canvas.saveState() canvas.setFont('Times-Bold',16) canvas.drawString(200,750,"Header") canvas.restoreState() # Define a function to create a footer def footer(canvas, doc): canvas.saveState() canvas.setFont('Times-Roman',9) canvas.drawString(inch, 0.75 * inch,"Footer") canvas.restoreState() # Create a frame frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal') # Create a page template with the header and footer template = PageTemplate(id='test', frames=frame, onPage=header, onPageEnd=footer) # Add the page template to the document self.doc.addPageTemplates([template]) |
The above code outlines the process of adding headers and footers to your pages. We first define functions to create our header and footer. These functions take a canvas and a document as arguments. The canvas is used to draw the header and footer on the page. We then create a Frame and a PageTemplate for our page, specifying the header and footer functions. Finally, we add the page template to our document.
Setting Watermarks
ReportLab allows you to add watermarks to your PDFs. You can add a watermark to all or selected pages using the PageBegin and PageEnd events.
def set_watermarks(self): # Define a function to add a watermark def add_watermark(canvas, doc): canvas.saveState() canvas.setFont('Times-Roman',30) canvas.setFillColorRGB(0.5,0.5,0.5) canvas.rotate(45) canvas.drawString(200,400,"Watermark") canvas.restoreState() # Create a canvas c = canvas.Canvas("watermark.pdf", pagesize=letter) # Add the watermark c.doForm(add_watermark) # Save the document c.save() |
The code above demonstrates how to add watermarks to your PDFs. We first define a function to add our watermark. This function takes a canvas and a document as arguments. The canvas is used to draw the watermark on the page. We then create a Canvas for our document and add the watermark to our page using the doForm method. Finally, we save our document.
Generating Table of Contents
ReportLab provides a TableOfContents class that you can use to generate a table of contents for your document.
def generate_table_of_contents(self): # Create a table of contents toc = TableOfContents() # Add the table of contents to the story self.story.append(toc) |
The above snippet shows how to generate a table of contents for your document. We first create a TableOfContents object for our table of contents. Finally, we add our table of contents to the story.
Adding PDFs to Existing PDF
You can add existing PDFs to your document using the PdfReader and PdfWriter classes from the pdfrw library.
def add_pdfs(self): # Read the source PDF source = PdfReader('source.pdf') # Create a PDF writer writer = PdfWriter() # Add the first page of the source PDF to the writer writer.addPage(source.pages[0]) # Write the output PDF writer.write('output.pdf') |
The code segment above illustrates how to add existing PDFs to your document. We first read our source PDF and create a PdfWriter for our output PDF. We add the first page of our source PDF to our writer. Finally, we write our output.
Summary about PDF reports development in ReportLab
ReportLab is a powerful library for creating PDF reports in Python. It offers a wide range of features, including text formatting, image insertion, chart creation, and more. With ReportLab, you can generate professional-quality PDF reports with ease.
This guide has walked you through the process of creating headers of different sizes, formatting paragraphs, inserting graphics and charts, setting page headers and footers, adding watermarks, generating a table of contents, and adding existing PDFs to your document. Each of these functionalities was encapsulated in a separate method within a Python class, demonstrating the modular and flexible nature of the ReportLab library.
References
- ReportLab User Guide: https://www.reportlab.com/docs/reportlab-userguide.pdf The official user guide for ReportLab, providing a comprehensive overview of the library’s features and how to use them.
- ReportLab API Documentation: https://www.reportlab.com/apis/reportlab/ The official API documentation for ReportLab, offering detailed information about the classes, methods, and functions available in the library.
- ReportLab GitHub Repository: https://github.com/Distrotech/reportlab The official GitHub repository for ReportLab, containing the source code for the library, as well as examples and tests.
- Python for PDF Generation: https://realpython.com/pdf-python/ A tutorial on Real Python that covers how to generate PDFs in Python using several libraries, including ReportLab.
- Creating PDF Reports with Pandas, Jinja and WeasyPrint: https://pbpython.com/pdf-reports.html A tutorial on Practical Business Python that covers how to create PDF reports with Python, including how to use ReportLab to create complex PDF layouts.