Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
pdf response   3   30702
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   3   30702
3 comments on 'How To Display Pdf In Browser In Django Instead Of Downloading It'
Login to comment

Narayan Rao Sept. 4, 2020, 9:58 a.m.
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!
Dharmekar Aishwarya Dec. 15, 2022, 4:49 p.m.
can you upload full code of this ? include form and url
Anurag Dec. 20, 2022, 2:49 p.m.
Hi Dharmekar, I can not upload the full code as that is the part of a larger private project. However I would love to assist you over email.

Related Articles:
Automating PDF generation using Python reportlab module
Generating PDF using python reportlab module, Adding table to PDF using Python, Adding Pie Chart to PDF using Python, Generating PDF invoice using Python code, Automating PDF generation using Python reportlab module...
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...
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...
DigitalOcean Referral Badge

© 2022-2023 Python Circle   Contact   Sponsor   Archive   Sitemap