How to show a PDF file in a Django view?

Viewed 69568

Is it possible to show a PDF file in the Django view, rather than making the user have to download it to see it?

And if it is possible, how would it be done?

This is what I have so far -

@login_required
def resume(request, applicant_id):

    #Get the applicant's resume
    resume = File.objects.get(applicant=applicant_id)
    fsock = open(resume.location, 'r')
    response = HttpResponse(fsock, mimetype='application/pdf')

    return response
12 Answers

it worked for me

import re, os
import os
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def export_auto_doc(request):
    name = request.GET.get('name', "")
    filename = "path/to/file"+name+".pdf"
    try:
        if not re.search("^[a-zA-Z0-9]+$",name):
            raise ValueError("Filename wrong format")
        elif not os.path.isfile(filename):
            raise ValueError("Filename doesn't exist")
        else:
            with open(filename, 'r') as pdf:
                response = HttpResponse(pdf.read(), content_type='application/pdf')
                response['Content-Disposition'] = 'inline;filename='+name+'.pdf'
                return response
            pdf.closed
    except ValueError as e:
        HttpResponse(e.message)

Use iframe url=url of pdf tag and give url of that pdf and make sure that your user will have full control of the project then pdf will be displayed on web screen

def pdf_view(request,pdfSlug):
     a = Pdf.objects.get(pdf_slug=pdfSlug)
     with open(str(a.pdf_file.path), 'rb') as pdf:
         response = FileResponse(pdf.read(), content_type='application/pdf')
         response['Content-Disposition'] = 'filename=a.pdf'
         return response
    pdf.closed

look this i'ts warked for me

Related