PDF Invoice generation in Python using Reportlab by using sales and product data using template
Keep the water mark at the starting so all other lines and text will appear over this.
To draw a vertical line we have to keep the x1 and x2 value same
To draw a horizontal line we have to keep the y1 and y2 value same
We can also use default font styles and a list is available by using getAvailableFonts() method
While using currency it is better to right align the string by using drawRightString()
Date is taken as today’s date by using date library.
There are three files used and the library ReportLab is used to write the PDF file.
the invoice_data.py file can be used to get data from different database and other data sources to generate the Invoice. Here some sample data is stored inside the file.
invoice_data.py
This file stores sample data for product and sales inside two dictionary and variables like tax rate discount rate are set here.
my_prod is a dictionary having product_id as key and product name , price as value list.
my_sale is a dictionary having product_id as key and quantity sold as value.
my_sale={1:2,3:2,7:1,4:3,6:5,5:3,2:1,9:1,10:3}
We have discount and tax rate as variables inside this file.
discount_rate=10 # 10% discount
tax_rate=12 # tax rate in percentage
temp_invoice.py
This is the template file where the blank design of the invoice is available inside the function my_temp(). This function is called inside the main file to show the blank invoice.
This file draws all lines , add text and place the top logo on the canvas. Font family is changed to available default fonts.
invoice.py
This is the main file and by using the template ( temp_invoice.py ) and the data ( invoice_data.py ) it creates the pdf document.
from temp_invoice import my_temp # import the template
from invoice_data import * # get all data required for invoice
By using for loop all sales data are displayed with quanity and price. Here for price and total drawRightString() is used.
for items in my_sale:
c.drawString(0.1*inch,line_y*inch,str(my_prod[items][0])) # p Name
c.drawRightString(4.5*inch,line_y*inch,str(my_prod[items][1])) # p Price
c.drawRightString(5.5*inch,line_y*inch,str(my_sale[items])) # p Qunt
sub_total=my_prod[items][1]*my_sale[items]
c.drawRightString(7*inch,line_y*inch,str(sub_total)) # Sub Total
total=round(total+sub_total,1)
line_y=line_y-row_gap