Create PDF file in Django Dynamically

In this tutorial, we will learn how to create dynamic PDF in Django.
Steps to follow:
1. Start your Django project.
2. Start your app inside the project named codespeedy.
3. Define a function named pdf_view in
4. In define the path.

Start Your Django project:

Create a project named codespeedy in the current folder using the command line django-admin startproject codespeedy.

This will create a project in your current working directory.

Start Your app:

We will create an app inside our project for which we need to check our current directory. If it shows the current directory as codespeedy write django-admin startapp create_pdf.

If it shows the folder outside the codespeedy folder write cd codespeedy it will create an app inside the project, write django-admin startapp create_pdf. Basically, we need to create our app inside our project.

Define the function in

Now we will define a function named pdf_view in inside our app. That function will generate PDF and we will define a function to write “I love codespeedy” in PDF on specific co-ordinates.
Here’s the code to accomplish this task which is the most essential part.

from reportlab.pdfgen import canvas
from django.http import HttpResponse
def pdf_view(request): 

    response = HttpResponse(content_type='application/pdf') 
    response['Content-Disposition'] = 'inline;'
    pdf = canvas.Canvas(response)
    pdf.drawString(200, 200, "I Love CodeSpeedy" ) 
    return response

First, import the above toolkit and libraries to work which is used later.

First, define the content type as application/pdf which will generate PDF. After that use content-disposition which functions to either download or open it in the browser. We can use inline to view PDF in our browser. We will give the response as the parameter to the canvas and pass it into variable pdf. Then use function drawstring and pass parameters which are co-ordinates of x and y respectively followed by the string you want to insert at that particular co-ordinates.

pdf. save() will save our pdf and return our required pdf.

Define the path in

We have successfully created a function to create our pdf dynamically but we haven’t defined a specific path to navigate to our PDF just made.

We need to define it inside our which is present in our project. So open and make these changes inside URL patterns provided to you-


We have created the function and also we specified our path.

Now we will try to open it in our browser and navigate to the URL specified and check whether it functions properly or not.

Write python runserver in your terminal. It will show you the link to the localhost where you will be able to see your pdf just created.

You can append /pdf_view after the localhost link i.e or

You will be able to see your pdf like-

create PDF dynamically in Django

I hope you like this tutorial.

Happy Coding!

Leave a Reply

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