Django Generate PDF from HTML View Example
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 ProjectIn 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 exampleStep 2 : Create a App
python3 manage.py startapp pdfStep 3 : Update setting.py
In this step we require to do two things in our settings.py 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 settings.py file:
Next, you need to add it in the settings.py file as follows:
.... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pdf', ]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 xhtml2pdfStep 5 : Creating the Views
In this step, we need to create the views for performing fetch record to the database.Open the pdf/views.py file and add:
pdf/views.pyfrom 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 data.next, open the pdf/templates/index.html file and the add:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django Generate PDF From Html View PDF And Download</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> </head> <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">Tuts-Station.com</span></h4> </div> <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> </div> </div> </div> </div> </div> </div> </div> </body> </html>
next, open the pdf/templates/viewPdf.html file and the add:
<head> <style> table, th, td { border:1px solid black; font-size: 15px; text-align: center; padding: 5px 5px; } .user-header{ text-align: center; font-size: 20px; } </style> </head> <body> <div class="row"> <div class="col-md-12 user-header"> <h1>Users List</h1> </div> </div> <!-- HTML Content --> <table class="table"> <tr> <th>Username</th> <th>Email</th> </tr> {% for user in users %} <tr> <td>{{user.username}}</td> <td>{{user.email}}</td> </tr> {% endfor %} </table> </body> </html>Step 7 : Creating Urls
In this section, we’ll create the urls to access our views.Go to the urls.py pdf/urls.py file and update it as follows:
pdf/urls.pyfrom 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 urls.py your root project folder lets update the file.
example/urls.pyfrom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), 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 manage.py runserver
Next, go to the http://localhost:8000/ address with a web browser.
Preview PDF:I Hope It will help you....