Python ReportLab Module
ReportLab is the standard library for generating PDFs in Python. It allows you to create complex documents with custom layouts, graphics, and charts directly from code.
Installation
pip install reportlab
Basic Usage
The canvas object is the primary interface for generating PDFs.
from reportlab.pdfgen import canvas
def hello(c):
c.drawString(100, 750, "Hello World")
c = canvas.Canvas("hello.pdf")
hello(c)
c.showPage()
c.save()
Coordinate System
ReportLab uses a coordinate system where (0,0) is at the bottom-left corner of the page. The default unit is points (1/72 inch).
Drawing Shapes
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
c = canvas.Canvas("shapes.pdf", pagesize=letter)
# Draw a line
c.line(100, 700, 500, 700)
# Draw a rectangle (x, y, width, height, fill=0/1)
c.rect(100, 600, 200, 50, fill=1)
# Draw a circle
c.circle(300, 500, 30, fill=1)
c.save()
Platypus (High-Level Layout)
For complex documents, use PLATYPUS (Page Layout and Typography Using Scripts). It handles page breaks and flow automatically.
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
doc = SimpleDocTemplate("complex.pdf")
styles = getSampleStyleSheet()
story = []
story.append(Paragraph("This is a Title", styles["Title"]))
story.append(Spacer(1, 12))
story.append(Paragraph("This is a normal paragraph that will wrap automatically.", styles["Normal"]))
doc.build(story)