from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
my_path='E:\\testing\\my_pdf\\my_pdf.pdf'# file path
c = canvas.Canvas(my_path,bottomup=1,pagesize=A4)
w,h=A4 # width and height of the page
xlist = [20, 70, 120, 170] # Horizontal coordinates
ylist = [h - 20, h - 70, h - 120, h - 170] # vertical
c.grid(xlist, ylist) # adding grid
c.save() # stores the file and close the canvas
Adding text to the grid
c.drawString(70,h-70,"plus2net") # write text
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
- reportlab.pdfgen.canvas: Used to create PDF files.reportlab.lib.pagesizes.A4: Provides the A4 page size.
my_path='E:\\testing\\my_pdf\\my_pdf.pdf' # File path
c = canvas.Canvas(my_path, bottomup=1, pagesize=A4)
w, h = int(A4[0]), int(A4[1]) # Width and height as integers
- Define the file path where the PDF will be saved.l1 = [('id', 'name', 'class', 'mark', 'gender'),
(1, 'John Deo', 'Four', 75, 'female'),
(2, 'Max Ruin', 'Three', 85, 'male'),
(3, 'Arnold', 'Three', 55, 'male')] # Data to be used
- Create a list of tuples representing the data to be placed in the grid.
rows, cols = len(l1), len(l1[0]) # Rows and columns of the grid
width_cell, height_cell = 75, 20 # Width and height of each cell
- Calculate the number of rows and columns in the grid.xlist=list(range(20,width_cell*(cols+1),width_cell))
ylist=list(range(h-20,h-(height_cell*(rows+2)),-height_cell))
c.grid(xlist, ylist) # add the grid to Canvas
Data from the list of tuple is added to each cell by looping
#Adding Data inside each cell of the grid by looping
for i in range(rows):
for j in range(cols):
c.drawString(xlist[j]+2,ylist[i]-int(height_cell/1.5),
str(i) + str(j) +'-'+ str(l1[i][j]))
Save the pdf file as per the path given above.
c.save()
Full code is here
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
my_path='E:\\testing\\my_pdf\\my_pdf.pdf'# file path
c = canvas.Canvas(my_path,bottomup=1,pagesize=A4)
w,h=int(A4[0]),int(A4[1]) # Width and height as Integer
l1=[('id', 'name', 'class', 'mark', 'gender'),
(1, 'John Deo', 'Four', 75, 'female'),
(2, 'Max Ruin', 'Three', 85, 'male'),
(3, 'Arnold', 'Three', 55, 'male')] # data to be used
rows,cols=len(l1),len(l1[0]) # rows and columns of the grid
width_cell,height_cell=75,20 # Update to match the data
xlist=list(range(20,width_cell*(cols+1),width_cell))
ylist=list(range(h-20,h-(height_cell*(rows+2)),-height_cell))
c.grid(xlist, ylist) # add the grid to Canvas
#Adding Data inside each cell of the grid by looping
for i in range(rows):
for j in range(cols):
c.drawString(xlist[j]+2,ylist[i]-int(height_cell/1.5),
str(i) + str(j) +'-'+ str(l1[i][j]))
print(xlist,ylist) # print the list used for grid
c.save()
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.