Django Python Generate PDF Example

Published On: 02/07/2022 | Category: Django Python

Hi Dev,

This tutorial will give you example of django python generate pdf example. This tutorial will give you simple example of django pdf generator. let’s discuss about python generate pdf file. you'll learn python generate pdf from template.

Here i explained simply step by step example of how to generate and download PDF in django.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 startapp pdf
Step 3 : Update

In this step we require to do two things in our file, One is to change the path of template look up directory. Second one is to configure our media folder. Add the below lines to your file:

Next, you need to add it in the file as follows:

Step 4 : Install reportLab

First of all Django uses the ReportLab open-source PDF library to generate pdf files. This library needs to be installed using pip before using it.

pip install reportLab
Step 5 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the pdf/ file and add:

import io
from django.http import FileResponse
from reportlab.pdfgen import canvas

def pdf_view(request):
    # Create a file-like buffer to receive PDF data.
    buffer = io.BytesIO()

    # Create the PDF object, using the buffer as its "file."
    p = canvas.Canvas(buffer)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(220, 650, "Welcome To")

    # Close the PDF object cleanly, and we're done.

    # FileResponse sets the Content-Disposition header so that browsers
    # present the option to save the file.
    return FileResponse(buffer, as_attachment=True, filename='tuts-station.pdf')
Step 6 : Creating Urls

In this section, we’ll create the urls to access our views.Go to the pdf/ file and update it as follows:

from django.urls import path
from . import views

urlpatterns = [
    path('generate-pdf', views.pdf_view),

Next, we will require the modify the your root project folder lets update the file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the http://localhost:8000/generate-pdf address with a web browser.

Preview PDF:

I Hope It will help you....