You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 KiB

Reportlab Cheatsheet

In [ ]:
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.units import inch, mm

ReportLab PDF Library

What is the ReportLab PDF Library?

This is a software library that lets you directly create documents in Adobe's Portable Document Format (PDF)using the Python programming language.

tip: the Reportlab Userguide, https://www.reportlab.com/docs/reportlab-userguide.pdf

Canvas

In [ ]:
Canvas?
In [ ]:
# Make a Canvas object, bottomup=0 will put the 0,0 at the lop-left (instead of bottom-left)
c = Canvas("pdf/reportlab-cheatsheet.pdf", pagesize=A4, bottomup=0)
In [ ]:
# Add a page
c.showPage()
In [ ]:
# Save the PDF
c.save()

Shapes

In [ ]:
c.circle?
In [ ]:
c.circle(20*mm, 20*mm, 10*mm, stroke=0, fill=1)
In [ ]:
c.rect?
In [ ]:
c.rect(40*mm, 40*mm, 10*mm, 10*mm, stroke=1, fill=0)
In [ ]:
c.roundRect?
In [ ]:
c.roundRect(60*mm, 60*mm, 50*mm, 50*mm, 5*mm, stroke=1, fill=0)
In [ ]:
c.showPage()
In [ ]:
 

Fonts

In [ ]:
# Reportlab comes with a set of fonts
c.getAvailableFonts()
In [ ]:
c.setFont('Courier', 72)
In [ ]:
# Or you can import fonts
from reportlab.pdfbase.ttfonts import TTFont, pdfmetrics

fontpath = "fonts/OSP-DIN.ttf"
font =  TTFont('OSP-DIN', fontpath)
pdfmetrics.registerFont(font)
In [ ]:
c.setFont('OSP-DIN', 72)
In [ ]:
c.drawCentredString(105*mm, 50*mm, "Hello :)!")
In [ ]:
c.showPage()
In [ ]:
 

Colors

In [ ]:
# Choose a RGB/CMYK color

# Fill-color
c.setFillColorRGB(255,0,0)
c.setFillColorCMYK(0,1,0,0)

# Stroke-color
c.setStrokeColorRGB(255,255,0)
c.setStrokeColorCMYK(0,0,1,0)
In [ ]:
# Or choose one of the embedded colors from Reportlab
from reportlab.lib.colors import pink, magenta, red, blue

c.setFillColor(magenta)
c.setStrokeColor(red)
In [ ]:
c.setFont('OSP-DIN', 72)
c.drawCentredString(105*mm, 50*mm, "Hello :)!")

c.rect(105*mm, 150*mm, 50*mm, 50*mm, stroke=1, fill=1)
In [ ]:
c.showPage()
In [ ]:
 

Lines

In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 

Text

In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 

Images

In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]: