Show a PDF file in Django instead of downloading
In this tutorial, we will be learning how to show a PDF file in Django instead of downloading. It is very simple if you know even a bit about Django. So lets start-
- Start an app named pdfshow.
- Create an app inside your project named show_pdf.
- Define a function in views.py
- Define URL path to navigate into the link.
Start an app named pdfshow
To start an app, open your terminal and write-
django-admin startproject pdfshow
Hit enter, it will create a project with the above name. It will contain some files and folders, we dont need to do anything to it.
Create an app show_pdf
Now, move inside your project using command-
cd pdfshow
And then create an app using-
django-admin startapp show_pdf
Hopefully you have created the project and app correctly.
Define a function named pdf_view
Without any further delay move to the views.py file under your app. First of all import HttpResponse which will be used later. Define a function named pdf_view, then open a file using path where you saved the pdf, we will accomplish this by reading in binary format. Then we will send HttpResponse as pdf and then display it in inline mode that means opening it in browser instead of downloading it. At last, return the response.
The code for the above theory is attached below-
from django.shortcuts import render from django.http import HttpResponse def pdf_view(request): with open('E:\mypdf.pdf', 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = 'inline;filename=mypdf.pdf' return response
Defining URL path
You are at the last step to view your pdf in browser. You just need to tell Django where to go. So let’s define path for our project.
urlpatterns = [ path('admin/', admin.site.urls), path('view-pdf/', views.pdf_view,name='pdf_view'), ]
This is the code for urlpatters, you can replace it using your function name.
python manage.py runserver
When you will execute this, you will be able to see screen like this on your default browser.
Don’t worry! you just need to move to a new URL you have just created to view your pdf. Just add/view-pdf in your URL. You will be moved to your pdf.
I hope you enjoyed reading this tutorial more than I enjoyed writing it! Feel free to comment and share your reviews. Have a nice day!
Leave a Reply