Create a pdf with reportlab

The module reportlab seems very good to make pdf files. This is the first post about this library. Let’s start with making a simple new pdf with some text like our hello world script.

I have used this module to create a nice application that adds a page with text to an existing pdf file (made to add an evaluation to tests) in this post here.

This code was taken from the Pythonvsmouse blog. You can find more documentation here with some useful code snippets.

from reportlab.pdfgen import canvas
import os


c = canvas.Canvas("hello.pdf")
c.drawString(100, 700, "First time using reportlab")
c.save()

os.startfile("hello.pdf")

You start from the bottom. To print the text at the start you need to pyt something like 700 as the height.

This is what you should come up to

In the following video there is this code above, just to show how easy it is. The audio is not so good, sorry.


Letter size

The default size of the page is a4. If you want letter size, add this to the code when you use the Canvas class, the pagesize argument=letter, like you see down here:

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

canvas = canvas.Canvas('myfile.pdf', pagesize=letter)
width, height = letter

How to set fonts

To set the size and tyope of the fonts, use a code like this

canvas.setFont('Helvetica', 12)

Draw lines

You can draw lines with this code.

  • first you set the width of the line
  • then you give the coordinates
canvas.setLineWidth(.3)
canvas.line(378,723,580,723)

 

Video 1: reportlab hello world

In the next post we will go further into this module to see what we can do with a pdf and python.


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.