VOOZH about

URL: https://www.geeksforgeeks.org/python/generate-a-pdf-in-django/

⇱ Generate a PDF in Django - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate a PDF in Django

Last Updated : 23 Jul, 2025

We will build a Django app that lets users enter book details and download them as a formatted PDF. We’ll use Django for the form and data handling and ReportLab to generate the PDF file. Step-by-step, we will learn how to set up the project, create models and views and output a downloadable PDF catalog.

Create a New Django Project and App

Prerequisites:

Run the Following Command:

django-admin startproject test_project
cd test_project
python manage.py startapp testapp

Register the App

In test_project/settings.py, add your app to INSTALLED_APPS:

INSTALLED_APPS = [
...
'testapp',
]

Create the Model

testapp/models.py:

This code represents a simple Django model for storing information about books, including their title, author and publication year.

Create the Form

testapp/forms.py:

This code sets up a Django form, BookForm, that is connected to the Book model and includes specific fields for creating or editing book instances with title, author and publication year attributes.

Create Views

testapp/views.py: Here is the code explanation of the views:

  • Import necessary modules.
  • home function: It is a simple input form which take Title, Author and, Publish Year as an Input, that is saved in the database.
  • generate_pdf function: This view function is called when a user requests a PDF. It uses generate_pdf_file to create a PDF and returns it as a downloadable attachment with the filename "book_catalog.pdf."
  • generate_pdf_file function: Imports BytesIO from io to create an in-memory buffer for the PDF. Initializes a PDF canvas (p) on the buffer. Retrieves all books from the Book model. Adds "Book Catalog" as the PDF title at coordinates (100, 750). Iterates through the books: Adds book details (title, author, year) to the PDF at decreasing Y-coordinates. Each book's details are printed with a vertical offset of -20 units. Calls showPage() to end the current page and save() to finish creating the PDF. The buffer is reset and returned. It now contains the PDF content.

Set Up URLs

testapp/urls.p: This is to set in the URLs of the app.

test_project/urls.py: This is to set in the Urls of the project folder.

Create Template

Directory structure:

testapp/
└── templates/
└── testapp/
└── create_user_profile.html

Create the template:

testapp/templates/testapp/create_user_profile.html

Make and Apply Migrations

By the following commands you can migrate the data into the database.

python manage.py makemigrations
python manage.py migrate

Run the Server

python manage.py runserver

Output:

👁 Screenshot-from-2023-09-10-16-36-59
Generate and Download PDF

The downloaded PDF:

👁 Screenshot-from-2023-09-19-00-26-08
Downloaded PDF
Comment