ReportLab has a library for generating PDFs from Python. The following example will show how a PDF can be created using this library. The PDF will contain a title and a table.
The first part of the script imports a few of the reportlab objects and sets up a few variables for stuff like titles.
from reportlab.platypus import *
from reportlab.rl_config import defaultPageSize
import reportlab.lib.colors
from reportlab.lib.units import inch
PAGE_HEIGHT=defaultPageSize[1]
Title = "Bill"
Next, we create a function that will be called to format the first page. This prints the title and adds the string “Sample bill” at the end of the page. You can consider this as a template for the first page. A similar function can be created for the following pages.
def myFirstPage(canvas, doc):
canvas.saveState()
canvas.setFont('Times-Bold',16)
canvas.drawString(108, PAGE_HEIGHT-108, Title)
canvas.setFont('Times-Roman',9)
canvas.drawString(inch, 0.75 * inch, "Sample bill %s" % doc.page)
canvas.restoreState()
Actually building the PDF is done in the go function. This takes a list of elements and builds the document. The name of the output file is bill.pdf .
def go():
Elements.insert(0,Spacer(0,inch))
doc = SimpleDocTemplate('bill.pdf')
doc.build(Elements,onFirstPage=myFirstPage)
The Elements list is defined next, as well as a temporary data list. The data list is filled from a file. We loop over that file and take all the lines that start with EVENTS. These lines are then split into pieces and we store the 12th and second part. This is appended to the data list. It’s added twice so that the output will be more than 1 page long.
The data is given to the Table class, which will construct a table in the PDF. A style option is given for the gridlines, which in this case will be of size 0.5 and grey.
This is then added to the Elements list and processed by the go function. Other types of elements such as paragraphs can also be added. The documentation has more information on that.
Elements = []
data=[]
for l in open('exp_30_21775_1'):
if l.startswith('EVENTS '):
parts=l.split('|')
data.append( [parts[11], parts[1] ] )
data.append( [parts[11], parts[1] ] )
t=Table(data,style=[('GRID',(0,0),(-1,-1),0.5,reportlab.lib.colors.grey),])
Elements.append(t)
go()
All in all, this is a very nice library. The output file can be found here .
Copyright (c) 2024 Michel Hollands