Hi friends, Welcome to HTML To PDF Django Tutorial. Sharing HTML files is very difficult task because of incompatibilities across different browsers.So we need to have convert HTML files into PDF format for easily sharing.In this tutorial we will learn how to convert HTML files into PDF in python.
Files of a web page is written in HTML(Hyper Text Markup Language).Portable Document Format (PDF) is a file format used to present and exchange documents reliably, independent of software, hardware, or operating system
When we convert a webpage into pdf ,all the associated files such as HTML,images, Adobe FLA files, Cascading Style Sheets, text files, image maps, and forms are also concerned in conversion process.The converted pdf files are similar to the original webpage.So now let’s start converting HTML files into PDF.
Converting HTML To PDF Django Tutorial
Converting HTML to Pdf in Django is not more difficult.Now, we will learn how to implement it.
xhtml2pdf library
- Python provides xhtml2pdf library to convert html files into pdf files.
- xhtml2pdf is a html2pdf converter using the ReportLab Toolkit, the HTML5lib and pyPdf.
- It supports HTML 5 and CSS 2.1 (and some of CSS 3). It is completely written in pure Python so it is platform independent.
- The main benefit of this tool that a user with Web skills like HTML and CSS is able to generate PDF templates very quickly without learning new technologies.
- For more information about xhtml2pdf refer this link.
Installing xhtml2pdf
This can be installed similar to other typical python library.Go to terminal and run the following command.
1 2 3 |
pip install xhtml2pdf |
Creating a new project
Now create a new project and named it as your wish.If you are getting problem in creating new project then don’t worry just check this link.
Opening Project in PyCharm
Now open PyCharm(i am using PyCharm IDE but you can use anyone) and open the project we created with power shell.
Creating utils.py file
Now come inside your app i.e., HTMLtoPDF and create a utils.py file.
Inside this file we will implement render_to_pdf
function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
from io import BytesIO #A stream implementation using an in-memory bytes buffer # It inherits BufferIOBase from django.http import HttpResponse from django.template.loader import get_template #pisa is a html2pdf converter using the ReportLab Toolkit, #the HTML5lib and pyPdf. from xhtml2pdf import pisa #difine render_to_pdf() function def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() #This part will create the pdf. pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None |
Creating a Template
Now create a directory templates and inside this create a html file and named it as invoice.html.Now write the following code in invoice.html .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django HTMLtoPDF Tutorial</title> </head> <body> <h1>HTML To PDF</h1> <b>I'm building web-based, data-driven apps using Django. <br> Eventually (or unfortunately), I will need to generate some reports that are printer-friendly. <b> Logically, PDF is the format for such files... <br> so how am I going to convert my xHTML and CSS to a nice-looking PDF document?<br> The Django Book has a whole chapter dedicated to Generating Non-HTML Content.<br> They seem to to be fond of ReportLab ToolKit.<br> The caveat here, though, is that you need to know a bit about the internals of a PDF document.<br> If you're familiar with this, the ReportLab toolkit seems to be the way to go! It has many features, and it seems to be a powerful PDF-generating tool. </b> </body> </html> |
“A Django Template is a sequence of Text that helps in separation of the presentation layer of a document from its data”. For understanding templates deeply you can read this link.
Rendering Template
- Now for rendering template we have to create a view.
- Now inside our app(HTMLtoPDF) create a views.py file.
- If you are not familiar with what is view then don’t worry – Views are just python function. Views take user request and give them back something. Like user will request there profile and view will show him his profile.And if you want to know more about views then this link is helpful for you.
- Write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from django.http import HttpResponse from django.views.generic import View #importing get_template from loader from django.template.loader import get_template #import render_to_pdf from util.py from .utils import render_to_pdf #Creating our view, it is a class based view class GeneratePdf(View): def get(self, request, *args, **kwargs): #getting the template pdf = render_to_pdf('invoice.html') #rendering the template return HttpResponse(pdf, content_type='application/pdf') |
What we did?
- We have just created a view GeneratePdf(View) and pass the view as parameter.
- Define a get() method but of course you can use any other method.
- Inside the function we create our template from render_to_pdf.
- And then finally rendering the template in HttpResponse.
- content_type=’application/pdf’ means MIME types. application/pdf is used for pdf format.
Defining a URL
Now we need to define a URL to see our template.For this we have to do such things –
- Inside urls.py file of the project and write the below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from django.contrib import admin from django.urls import path #This will import our view that we have already created from .views import GeneratePdf urlpatterns = [ path('admin/', admin.site.urls), #we have defined a url pdf/ #and whenever the user will request this url pdf<strong>,</strong>check the file urls.py inside app HTMLtoPDF. path('pdf/', GeneratePdf.as_view()), ] |
Defining Template Directory in Settings
And now this is the most important point to be noted.If we don’t do this then get a template not found error.For avoiding this error, we have to set templates/ in settings.py file.It is essential to render the pdf.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates/'], #Add this line 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] |
Running Your Project
- Now we have to run our project to see output.
- For running, go to terminal and run the following command.
1 2 3 |
python manage.py runserver |
- After running this command you will see the following information.
- Now click on server that will navigate you to the browser.
- Now enter this URL http://127.0.0.1:8000/pdf/ and this will show the template which we have created.
Finally, our project is running successfully and you can see now how our HTML file converted into PDF.
So that’s all for this HTML To PDF Django Tutorial. Feel free to leave your comments if having any queries regarding this HTML To PDF Django Tutorial. And you like this then please share with your friends.We will do some more cool stuffs in upcoming tutorials. Thank You 🙂