Make a formal letter in pdf with Python and reportlab

This code can be a start to make a document in pdf, via Python. I’ve taken the example from mouse vs python and I tried to make it more readable and easy to modify. I wish it can help you make your onw.

You need to install reportlab with

pip install reportlab

The code

import time
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
doc = SimpleDocTemplate("form_letter.pdf",pagesize=letter,
                        rightMargin=72,leftMargin=72,
                        topMargin=72,bottomMargin=18)
import os


page=[]
magName = "Pythonista"
issueNum = 12
subPrice = "99.00"
limitedDate = "03/05/2010"
freeGift = "tin foil hat"

styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))


def add_image(img):
    im = Image(img, 2*inch, 2*inch)
    page.append(im)


def add_space():
    page.append(Spacer(1, 12))


def add_text(text, space=0):
    if type(text)==list:
        for f in text:
            add_text(f)
    else:
        ptext = f'<font size="12">{text}</font>'
        page.append(Paragraph(ptext, styles["Normal"]))
        if space==1:
            add_space()
        add_space()


# =============================== The content =======================
# ============================== of the document ====================
add_image("python_logo.png")
add_text(time.ctime())
add_text([
"""Giovanni Gatto
Via Leonardo Da Vinci""".splitlines()])


add_text(["""We would like to welcome
you to our subscriber base for {} Magazine!
You will receive {} issues at the excellent
introductory price of ${}.
Please respond by
{} to start receiving 
your subscription and get the
following free gift: {}.""".format(
    magName,
    issueNum,
    subPrice,
    limitedDate,
    freeGift),
    "Thank you very much and we look forward to serving you.",
])

# ===========================================================

doc.build(page)

os.startfile("form_letter.pdf")

the result


A much cleaner version for Mac Os

This version is much cleaner (and it’s usable also for the windows system) than the version above, cause you can add all the text and also the images in a very easy and visually well organized way.

import time
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
doc = SimpleDocTemplate("form_letter.pdf",pagesize=letter,
                        rightMargin=72,leftMargin=72,
                        topMargin=72,bottomMargin=18)
import os


page=[]
styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))


def add_image(img):
    im = Image(img, 2*inch, 2*inch)
    page.append(im)


def add_space():
    page.append(Spacer(1, 12))


def add_text(text, space=0):
    if type(text)==list:
        for f in text:
            add_text(f)
    else:
        ptext = f'<font size="12">{text}</font>'
        page.append(Paragraph(ptext, styles["Normal"]))
        if space==1:
            add_space()
        add_space()

def show(text):
    "Prints all the lines in the text multiline string"
    text = text.splitlines()
    for line in text:
        if ".png" in line:
            add_image(line)
        elif "ctime()" in line:
            add_text(time.ctime())
        else:
            add_text(line)


# =============================== The content =======================

text = """
python_logo.png
time.ctime()

Giovanni Gatto
Via Leonardo Da Vinci
tel. 335556566

Hello,
This is a formal letter
    Thank you very much and we look forward to serving you.
"""
# ===========================================================

show(text)
doc.build(page)
os.system("echo form_letter.pdf")

 


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.