Django Export to PDF - display PDF in the browser and open-save file example
In this article I will show how to return a PDF response, which can also be used if you are just serving an existing PDF file
below Django’s FileSystemStorage class FileSystemStorage sets the base_url to the project’s MEDIA_ROOT.
View.py
#views.py from django.shortcuts import render, redirect from django.core.files.storage import FileSystemStorage from django.http import HttpResponse, HttpResponseNotFound def pdf_view(request): fs = FileSystemStorage() filename = 'mypdf.pdf' if fs.exists(filename): with fs.open(filename) as pdf: response = HttpResponse(pdf, content_type='application/pdf') #response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' #user will be prompted with the browser’s open/save file response['Content-Disposition'] = 'inline; filename="mypdf.pdf"' #user will be prompted display the PDF in the browser return response else: return HttpResponseNotFound('The requested pdf was not found in our server.')urls.py
#urls.py from django.contrib import admin from django.urls import path from myapp import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), #path('',views.index), url(r'^view-pdf/$', views.pdf_view, name='pdf_view'), ]url : http://127.0.0.1:8000/view-pdf/