Create a PDF file using pyPdf Python module

In this scenario, we will learn how to create a PDF file using pyPdf Python module. PyPDF2 is the extended version of the pyPdf module in python. So we are going to use the PyPDF2 module to create a new pdf file.

PyPDF2 is not a predefined module, so before using it we have to install it using command prompt as:

# Installation of PyPDF2 module
C:\Users>pip install PyPDF2

In the PyPDF2 module, we have many classes like PdfFileWriter and PdfFileReader, etc. In this tutorial, we use the PdfFileWriter class to create a pdf, So we have to import the PdfFileWriter class into our program.

# importing PdfFileWriter class
from PyPDF2 import PdfFileWriter

In the next step of our tutorial, we will open a new pdf file for writing contents into that file.

Opening the pdf file:


In the above step, we opened a file “pavan.pdf” using open() method in “wb” format (i.e combination of write mode and binary mode). Now let us create a pdf file using the PdfFileWriter class, open() method, and PyPDF2 module.

Example program to create a pdf file using pyPdf Python module

from PyPDF2 import PdfFileWriter as w
for i in range(5):
    pdf.addBlankPage(219,297) #a4 size dimensions

As the output of our program, we will able to see the PDF file that we have just created.

In the first line of our above script,  we imported the PyPDF2 module and also it’s class PdfFileWriter as w. In the second step of our script, we open the file using the open() method in the “wb” format. later using for loop we created five blank a4 size pages(dimensions of a4 219×297).

Here if we increase the range of for loop then the number of pages in our pdf also increases gradually. Using the addBlankPage() method we add a blank page into the file as a4 size dimensions. Finally using the write() method we write all the five blank pages into the pdf file “pavan.pdf” and close the file using the close() method.

Also, read: Read a particular pdf page

2 responses to “Create a PDF file using pyPdf Python module”

  1. S. Jayaram says:

    I found working code from your site only. Thank you . Great

  2. Petros says:

    A4 dimensions are 210x297mm not 219×297 as in your example.
    Great tutorial otherwise.

Leave a Reply

Your email address will not be published. Required fields are marked *