Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Data Structures Algorithms Interview Preparation Topic-wise Practice C++ Java Python Competitive Programming

Creating PDF Documents With Python


Difficulty Level : Medium ● Last Updated : 05 May, 2021

In this article, we will be learning how to create PDFs in Python. A very famous module named
pypdf2 is used to modify and read existing pdfs but its major disadvantage is that it cannot create
new pdf files. So Today we are looking to learn about another python module named reportlab
that helps us to create new pdf files and edit our heart’s content on it.

Module Required:

Reportlab: This module is used to handle PDF files.

pip install reportlab

Step-by-step Approach:

Step 1:

We start by importing the modules and classes. Canvas is used to draw things on the pdf, ttfonts
and pdfmetrics will help us to use custom TTF fonts in the pdf, and colors would help us to pick
colours easily without remembering their hex values.

Python3

# importing modules
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
fromyou
We use cookies to ensure reportlab.lib import
have the best browsing colors
experience on our website. By using our site, you acknowledge that you Got It !
have read and understood our Cookie Policy & Privacy Policy

Step 2:
Start Your Coding Journey Now! Login Register
Next, we initialize all the things we would b writing and drawing in the document to specific
variables to easily call them when needed.

Python3

# initializing variables with values


fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Technology'
subTitle = 'The largest thing now!!'
textLines = [
'Technology makes us aware of',
'the world around us.',
]
image = 'image.jpg'

Step 3:

Next, we initialize a canvas object with the name of the pdf and set the title to be documentTitle.

Python3

# creating a pdf object


pdf = canvas.Canvas(fileName)

# setting the title of the document


pdf.setTitle(documentTitle)

Step 4:

Next, we register our external font to the reportlab fonts using pdfmetrics and TTFont and
assigned it a name. Next, we set the new font with a size. Then we draw the string on the pdf
using the drawCentredString function that takes the x and y values as the center of the text to the
written and the left, right, top and bottom of the text are adjusted accordingly. Note that we need
the TTF file to be present in the folder to execute the commands.

Python3

# registering a external font in python


pdfmetrics.registerFont(
TTFont('abc', 'SakBunderan.ttf')
)

# creating the title by setting it's font


# and putting it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)

Step 5:

Next for the subtitle, we do the same thing except for this time the colour of the subtitle to be
blue, and this time we use a standard font that ships in natively with reportlab.

Python3

# creating the subtitle by setting it's font,


# colour and putting it on the canvas
pdf.setFillColorRGB(0, 0, 255)
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)

Step 6:

Next, we draw a line and then enter several lines of text that we defined earlier inside a list. The
first line defines the starting x and y position of the text. The next two lines set the font, font-size
and font-color of the text. The next two lines traverse through each element in the list and add it
as a line to the text. The last line draws the text to the screen.

Python3

# drawing a line
pdf.line(30, 710, 550, 710)

# creating a multiline text using


# textline and for loop
text = pdf.beginText(40, 680)
text.setFont("Courier", 18)
text.setFillColor(colors.red)

for line in textLines:


text.textLine(line)

pdf.drawText(text)

Step 7:

At last, we draw a picture on the pdf using the drawInlineImage function in which the parameters
are the path of the image and the x and y coordinates of the image. In this case, the image was
in the same directory as the py file, so according to the relative path, we need to write only the
name of the file with the extension, if it was in some other directory, a relevant correct relative
path should be used.

Python3

# drawing a image at the


# specified (x.y) position
pdf.drawInlineImage(image, 130, 400)

# saving the pdf


pdf.save()

Below is the complete program:

Python3

# importing modules
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors

# initializing variables with values


fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Technology'
subTitle = 'The largest thing now!!'
textLines = [
'Technology makes us aware of',
'the world around us.',
]
image = 'image.jpg'

# creating a pdf object


pdf = canvas.Canvas(fileName)

# setting the title of the document


pdf.setTitle(documentTitle)

# registering a external font in python


pdfmetrics.registerFont(
TTFont('abc', 'SakBunderan.ttf')
)

# creating the title by setting it's font


# and putting it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)

# creating the subtitle by setting it's font,


# colour and putting it on the canvas
pdf.setFillColorRGB(0, 0, 255)
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)

# drawing a line
pdf.line(30, 710, 550, 710)

# creating a multiline text using


# textline and for loop
text = pdf.beginText(40, 680)
text.setFont("Courier", 18)
text.setFillColor(colors.red)
for line in textLines:
text.textLine(line)
pdf.drawText(text)

# drawing a image at the


# specified (x.y) position
pdf.drawInlineImage(image, 130, 400)

# saving the pdf


pdf.save()

Output:

Attention geek! Strengthen your foundations with the Python Programming Foundation
Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the
Python DS Course. And to begin with your Machine Learning Journey, join the Machine
Learning - Basic Level Course

Like 1

Previous Next
MongoDB - copyTo() Method Multi-plot grid in Seaborn

RECOMMENDED ARTICLES Page : 1 2 3

01 Check if two PDF documents are


identical with Python
05 Working with Documents - Python
.docx Module
06, Mar 21 24, Dec 20

02 Send PDF File through Email using


pdf-mail module
06 Parsing and converting HTML
documents to XML format using
01, May 20 Python
23, Aug 21

03 Create XML Documents using Python


29, Apr 20 07 D3.JS (Data Driven Documents)
14, Jan 19

04 Count the number of Documents in


MongoDB using Python
08 Update all Documents in a Collection
using PyMongo
03, Jun 20 30, May 20

Article Contributed By : Vote for difficulty


Current difficulty : Medium
saikatsahana91
@saikatsahana91 Easy Normal Medium Hard Expert

Improved By : simranarora5sos

Article Tags : Picked, python-utility, Python

Improve Article Report Issue

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

Load Comments

WHAT'S NEW

Python Programming Foundation -Self Paced Course

View Details

Data Structures & Algorithms- Self Paced Course

View Details

Complete Interview Preparation

View Details

MOST POPULAR IN PYTHON

Python | os.path.isdir() method

Queue in Python

Python | Get unique values from a list

Python Classes and Objects

How to Install PIP on Windows ?

MORE RELATED ARTICLES IN PYTHON

Deque in Python

Python math function | sqrt()

Defaultdict in Python

Convert string to integer in Python

Python | Split string into list of characters

5th Floor, A-118,


Sector-136, Noida, Uttar Pradesh - 201305

feedback@geeksforgeeks.org

Company Learn News Languages Web Contribute


About Us Algorithms Top News Python Development Write an Article

Careers Data Technology Java Web Tutorials Improve an Article

In Media Structures Work & CPP Django Tutorial Pick Topics to Write

Contact Us SDE Cheat Career Golang HTML Write Interview


Sheet Business Experience
Privacy C# CSS
Policy Machine Finance Internships
SQL JavaScript
learning
Copyright Lifestyle Bootstrap Video Internship
Policy CS Subjects

Video
Tutorials

@geeksforgeeks , Some rights reserved

Sign In Sign Up

Username or email

Password

Remember me Forgot Password

Sign In

E-mail

Password

Institution/Organization

Sign Up

or
Google
Facebook

LinkedIn
GitHub

Why Create an Account?


By creating this account, you agree to our Privacy Policy & Cookie Policy.
Please enter your email address or userHandle.

Username/Email

Back to Login

Reset Password

You might also like