This space is available for advertisement. Please contact us if interested.
Advertise with us
pdf response   1   22214
How to display PDF in browser in Django instead of downloading it

In one of the previous article, we learned how to generate and return the PDF file in response. This was the right choice if you want to download the PDF file. But if you want to display PDF file inside the browser window then we need to make use of FileResponse.

Remember that browsers won't display PDF if proper plugins are not available.

Let's say you want to display the payslip of employees. Below is the directory structure where we are going to store the payslips.

   |    |-payslips
   |    |    |-2019
   |    |    |   |-january
   |    |    |   |-feburary
   |    |    |   |    |-6754599.pdf
   |    |    |   |    |-6754600.pdf

All the media files are stored in the media folder in the project root. We have further created more folders to segregate documents. Salary slips are stored year and month wise. Salary slip file name is [employee id].[extension], pdf in this case.

Now in view responsible to display payslip, write below code.

def payslip_view(request, employee):
data = dict()
data["employee"] = employee
if "GET" == request.method:
return render(request, "appname/payslip.html", data)

# else for post call, procced
post_data = request.POST.copy()
year = post_data.get("year", None)
month = post_data.get("month", None)

if not year or not month:
messages.error(request, "Please select year and month.")
return HttpResponseRedirect(reverse("appname:payslip", args=(employee,)))

filename = employee + ".pdf"
filepath = os.path.join(settings.MEDIA_ROOT, "payslips", year, month, filename)
return FileResponse(open(filepath, 'rb'), content_type='application/pdf')
except FileNotFoundError:
messages.error(request, "Payslip of Employee with Id " + employee + " doesn't exists for " + month + " " + year)
return HttpResponseRedirect(reverse("appname:payslip", args=(employee,)))

Import required classes/modules.

from django.contrib import messages
from django.http import HttpResponseRedirect, Http404, FileResponse
from django.shortcuts import render
from django.urls import reverse

from django.contrib.auth.decorators import login_required import os from django.conf import settings

You need to create another view which will display the HTML page with drop downs to select year and month for the logged in employee. Once the year and month are selected and form is submitted, post request is handled by the above view and payslip is displayed in the browser window. 

Host your Django project for free.

Top 5 Python Books.

pdf response   1   22214

Related Articles:
How to download data as CSV and Excel file in Django
How to download excel file in django, download data csv and excel file in django, excel file in python, csv and excel file in django python, download excel python-Django...
Python Requests Library: Sending HTTP GET and POST requests using Python
Python requests library to send GET and POST requests, Sending query params in Python Requests GET method, Sending JSON object using python requests POST method, checking response headers and response status in python requests library...
How to download large csv files in Django
How to download large csv file in Django, streaming the response, streaming large csv file in django, downloading large data in django without timeout, using django.http.StreamingHttpResponse to stream response in Django, Generating and transmitting large CSV files in django...
Generating and Returning PDF as response in Django
Creating PDF documents in Python and Django, Returning PDF as response in Django, Generating PDF from HTML template in Django, Using pdfkit and wkhtmltopdf in python and django...

1 thought on 'How To Display Pdf In Browser In Django Instead Of Downloading It'
Narayan Rao :
This is fantastic! I was struggling to get a pdf document displaying in the browser using Django. I was able to do this easily using FileResponse and the code shown. Thanks a lot!

Leave a comment:

*All Fields are mandatory. **Email Id will not be published publicly.

DigitalOcean Referral Badge

Get a .COM for just $5.98!

© 2021-2022 Python Circle   Contact   Sponsor   Archive   Sitemap   Partner Sites: PythonSnippets.Dev  99Dev.Tools