Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
automation pdf   1   33745
Automating PDF generation using Python reportlab module


We learned how to send emails with attachmentread emails from Gmail inbox and how to send messages to Microsoft teams channel.

When you are automating the mundane tasks, there might be cases when you have to generate PDF files. It could be invoices, reports, or simple documentation. In this article, we will see how to generate PDF files using Python's reportlab module.



Prerequisite:

First, we need to install reportlab module in a virtual environment. Activate the virtual environment and run the below command.

pip install reportlab


If you are using the Jupyter notebook, you can install the module as below.

import sys
!{sys.executable} -m pip install reportlab


installing module in jupyter lab




Generating PDF:

Let's start by generating a simple PDF with a title. 

from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus import Paragraph, Spacer, Table, Image
from reportlab.lib.styles import getSampleStyleSheet

styles = getSampleStyleSheet()
report = SimpleDocTemplate("/tmp/report.pdf")
report_title = Paragraph("A Complete Inventory of My Fruit", styles["h1"])
report.build([report_title])


Once this code is executed, a PDF file will be generated at location /tmp/report.pdf. The PDF file will have a title and have a heading (h1) style on the title.

report.build() method expects at least one flowable as a parameter. Flowables are sort of like chunks of a document that reportlab can arrange to make a complete report. Paragraph, Spacer, Table, and Image are examples of flowable.



Adding a table to PDF:

Let's say we have a dictionary of some items as below.

fruit = {
  "elderberries": 1,
  "figs": 1,
  "apples": 2,
  "durians": 3,
  "bananas": 5,
  "cherries": 8,
  "grapes": 13
}

We will create a table from this dictionary to add to the PDF file. To make a Table object, we need our data to be in a list-of-lists, sometimes called a two-dimensional array. We have our inventory of fruit in a dictionary. This is how we convert a dictionary into a list-of-lists.

table_data = []
for k, v in fruit.items():
    table_data.append([k, v])

print(table_data)


The output of the print statement will be

[['durians', 3], ['cherries', 8], ['elderberries', 1], ['figs', 1], ['apples', 2], ['grapes', 13], ['bananas', 5]]


Now create a Table flowable and add it to report in the order we want it to appear, after the title in this case.

report_table = Table(data=table_data)
report.build([report_title, report_table])


This will generate a simple table without any styles. Let's add border and alignment to the table.

from reportlab.lib import colors

table_style = [('GRID', (0,0), (-1,-1), 1, colors.black)]
report_table = Table(data=table_data, style=table_style, hAlign="LEFT")
report.build([report_title, report_table])


This will generate a PDF with the title and table.

table in pdf using reportlab python



Adding a pie chart:

We’re going to need to use the Drawing Flowable class to create a Pie chart

To add data to our Pie chart, we need two separate lists: One for data, and one for labels. Once more, we’re going to have to transform our fruit dictionary into a different shape. 

from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.piecharts import Pie
from reportlab.lib.units import inch


report_pie = Pie(width=3*inch, height=3*inch)

report_pie.data = []
report_pie.labels = []

for fruit_name in sorted(fruit):
    report_pie.data.append(fruit[fruit_name])
    report_pie.labels.append(fruit_name)
    
print(report_pie.data)
print(report_pie.labels)


Output:

[2, 5, 8, 3, 1, 1, 13]
['apples', 'bananas', 'cherries', 'durians', 'elderberries', 'figs', 'grapes']


The Pie object isn’t Flowable, but it can be placed inside of a Flowable DrawingNow add this chart to the report.

report_chart = Drawing()
report_chart.add(report_pie)
report.build([report_title, report_table, report_chart])


PDF will look like something as below after executing this code.


pie chart add in report using reportlab python


We will cover more points regarding generating PDF in upcoming articles.



- Here is a list of some awesome python books
Host your Django Application for free on PythonAnyWhere.
- If you want full control of your application and server, you should consider 
DigitalOcean.
- Create a
 DigitalOcean account with this link and get $100 credits.



automation pdf   1   33745
1 comment on 'Automating Pdf Generation Using Python Reportlab Module'
Login to comment

Spencerstok@Gmail.Com Nov. 19, 2020, 4:13 p.m.
Hi there, I'm facing issue in account activation. I have received the email but when i click on confirmation link it's redirecting me on 404 page.

Related Articles:
Django application to automate the WhatsApp messaging
Django application with REST API endpoints to automate the WhatsApp messaging. Automating WhatsApp web using selenium to send messages. Using selenium to automate whatsapp messaging. Sending bulk messages via whatsapp using automation. Source code Django application Whatsapp Automation...
Automating WhatsApp web using selenium to send messages
Automating WhatsApp web using selenium to send messages. Using selenium to automate whatsapp messaging. Sending bulk messages via whatsapp using automation....
Accessing Gmail Inbox using Python imaplib module
In this article, we are accessing Gmail inbox using IMAP library of python, We covered how to generate the password of an App to access the gmail inbox, how to read inbox and different category emails, how to read promotional email, forum email and updates, How to search in email in Spam folder, how to search an email by subject line, how to get header values of an email, how to check DKIM, SPF, and DMARC headers of an email...
Sending email with attachments using Python built-in email module
Sending email with attachments using Python built-in email module, adding image as attachment in email while sending using Python, Automating email sending process using Python, Automating email attachment using python...
DigitalOcean Referral Badge

© 2022-2023 Python Circle   Contact   Sponsor   Archive   Sitemap