Creating payment receipts is a common task, whether for an e-commerce website, a local store, or any business. In this article, we will learn how to generate transaction receipts as PDF files using Python.
We will use the reportlab library to create PDFs with tables, styles and headings.
Installation
Install "ReportLab" library using the following pip command:
pip install reportlab
Step-Wise Implementation
1. Import Required Modules: Import all the Python libraries needed to create the PDF, tables, and styles.
from reportlab.platypus import SimpleDocTemplate, Table, Paragraph, TableStyle
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
2. Prepare Data: The data for the receipt is organized in a list of lists. The first row contains the table headers.
DATA = [
["Date", "Name", "Subscription", "Price (Rs.)"],
["16/11/2020", "Full Stack Development with React & Node JS - Live", "Lifetime", "10,999.00/-"],
["16/11/2020", "Geeks Classes: Live Session", "6 months", "9,999.00/-"],
["Sub Total", "", "", "20,998.00/-"],
["Discount", "", "", "-3,000.00/-"],
["Total", "", "", "17,998.00/-"]
]
3. Create PDF Template: We create a base PDF document named receipt.pdf and set its page size to standard A4 dimensions.
pdf = SimpleDocTemplate("receipt.pdf", pagesize=A4)
4. Create Styles: Use ReportLab’s built-in sample style sheet and adjust the heading style.
styles = getSampleStyleSheet()
title_style = styles["Heading1"]
title_style.alignment = 1
Here, alignment = 1 centers the title on the page.
5. Create the Title: Create a title paragraph for the PDF.
title = Paragraph("GeeksforGeeks", title_style)
6. Create Table Style: Define the style for the table, including borders, grid lines, header color, text alignment, and background color.
style = TableStyle([
("BOX", (0, 0), (-1, -1), 1, colors.black),
("GRID", (0, 0), (-1, -1), 1, colors.black),
("BACKGROUND", (0, 0), (-1, 0), colors.gray),
("TEXTCOLOR", (0, 0), (-1, 0), colors.whitesmoke),
("ALIGN", (0, 0), (-1, -1), "CENTER"),
("BACKGROUND", (0, 1), (-1, -1), colors.beige)
])
Explanation:
- BOX: Draws a border around the entire table.
- GRID: Adds grid lines between all cells.
- BACKGROUND (0,0 to -1,0): Sets the header row’s background color to gray.
- TEXTCOLOR (0,0 to -1,0): Sets the header row text color to white.
- ALIGN: Centers text in all cells.
- BACKGROUND (0,1 to -1, -1): Sets the background color of all data rows to beige.
7. Create the Table: Create the table object and apply the style.
table = Table(DATA, style=style)
8. Build the PDF: Combine the title and table and build the PDF.
pdf.build([title, table])
Output
