Django Generate PDF from HTML View Example

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

Hi Dev,

Hello all! In this article, we will talk about django generate pdf from html view pdf and download example. this example will help you how to convert html to pdf python django. you'll learn django python html to pdf example. we will help you to give example of python generate pdf from html template.

In this article, you will learn to convert HTML pages to PDF using Django. You will see examples so that you can understand the concept better.

So, let's start the example follow my below steps..

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 xhtml2pdf Library

First of all we can use the xhtml2pdf library in Django to convert an HTML document into a PDF file. Let us see how to use this library.

pip install xhtml2pdf
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:

from django.shortcuts import render
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from django.views import View
from xhtml2pdf import pisa
from django.contrib.auth import get_user_model

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html  = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

#Opens up page as PDF
class ViewPDF(View):
    def get(self, request, *args, **kwargs):

        users= get_user_model().objects.all()
        context= {'users': users}
        pdf = render_to_pdf('viewPdf.html', context)
        return HttpResponse(pdf, content_type='application/pdf')

#Automaticly downloads to PDF file
class DownloadPDF(View):
    def get(self, request, *args, **kwargs):
        users= get_user_model().objects.all()
        context= {'users': users}
        pdf = render_to_pdf('viewPdf.html', context)

        response = HttpResponse(pdf, content_type='application/pdf')
        filename = "users.pdf"
        content = "attachment; filename=%s" %(filename)
        response['Content-Disposition'] = content
        return response

def index(request):
    return render(request, 'index.html')
Step 6 : Creating Templates

In this section, we’ll create the django templates to to render the user, open the pdf/templates/index.html file and the add:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Django Generate PDF From Html View PDF And Download</title>
    <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
<body class="bg-dark">
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-10">
                <div class="card">
                    <div class="card-header">
                        <h4>Django Generate PDF From Html View PDF And Download - <span class="text-primary"></span></h4>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-12 text-center">
                                <a class="btn btn-info" href="{% url 'pdf_view' %}" target="_blank">View PDF</a>
                                <a class="btn btn-info"  href="{% url 'pdf_download' %}">Download PDF</a>

next, open the pdf/templates/viewPdf.html file and the add:

    table, th, td {
        border:1px solid black;
        font-size: 15px;
        text-align: center;
        padding: 5px 5px;
        text-align: center;
        font-size: 20px;

    <div class="row">
        <div class="col-md-12 user-header">
            <h1>Users List</h1>

    <!-- HTML Content -->
    <table class="table">
        {% for user in users %}
        {% endfor %}
Step 7 : 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('', views.index),
    path('pdf_view/', views.ViewPDF.as_view(), name="pdf_view"),
    path('pdf_download/', views.DownloadPDF.as_view(), name="pdf_download"),

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 = [
     path('', include('pdf.urls')),
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/ address with a web browser.

Preview PDF:

I Hope It will help you....