Creating PDF Documents With Python - GeeksforGeeks

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 modulesfrom reportlab.pdfgen import canvasfrom reportlab.pdfbase.ttfonts import TTFontfrom reportlab.pdfbase import pdfmetricsfrom reportlab.lib import colors
Step 2:
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 valuesfileName = '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 objectpdf = canvas.Canvas(fileName) # setting the title of the documentpdf.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 pythonpdfmetrics.registerFont(    TTFont('abc', 'SakBunderan.ttf')) # creating the title by setting it's font# and putting it on the canvaspdf.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 canvaspdf.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 linepdf.line(30, 710, 550, 710) # creating a multiline text using# textline and for looptext = 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) positionpdf.drawInlineImage(image, 130, 400) # saving the pdfpdf.save()
 Below is the complete program:
Python3
# importing modulesfrom reportlab.pdfgen import canvasfrom reportlab.pdfbase.ttfonts import TTFontfrom reportlab.pdfbase import pdfmetricsfrom reportlab.lib import colors # initializing variables with valuesfileName = '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 objectpdf = canvas.Canvas(fileName) # setting the title of the documentpdf.setTitle(documentTitle) # registering a external font in pythonpdfmetrics.registerFont(    TTFont('abc', 'SakBunderan.ttf')) # creating the title by setting it's font# and putting it on the canvaspdf.setFont('abc', 36)pdf.drawCentredString(300, 770, title) # creating the subtitle by setting it's font,# colour and putting it on the canvaspdf.setFillColorRGB(0, 0, 255)pdf.setFont("Courier-Bold", 24)pdf.drawCentredString(290, 720, subTitle) # drawing a linepdf.line(30, 710, 550, 710) # creating a multiline text using# textline and for looptext = 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) positionpdf.drawInlineImage(image, 130, 400) # saving the pdfpdf.save()
Output:
simranarora5sos
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()