Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django/Python: Show pdf in a template

Tags:

python

pdf

django

I'm using django 1.8 in python 2.7.

I want to show a pdf in a template.

Up to know, thanks to MKM's answer I render it in a full page.

Do you know how to render it?

Here is my code:

def userManual(request):
    with open('C:/Users/admin/Desktop/userManual.pdf', 'rb') as pdf:
        response = HttpResponse(pdf.read(), content_type='application/pdf')
        response['Content-Disposition'] = 'inline;filename=some_file.pdf'
        return response
    pdf.closed
like image 579
zinon Avatar asked Mar 10 '23 23:03

zinon


2 Answers

The ability to embed a PDF in a page is out of the scope of Django itself, you are already doing all you can do with Django by successfully generating the PDF, so you should look at how to embed PDFs in webpages instead:

Therefore, please check:

Recommended way to embed PDF in HTML?

How can I embed a PDF viewer in a web page?

like image 131
Lorenzo Peña Avatar answered Mar 19 '23 07:03

Lorenzo Peña


views.py

from django.shortcuts import render
from django.http import FileResponse, Http404
def pdf(request):
    try:
        return FileResponse(open('<file name with path>', 'rb'), content_type='application/pdf')
    except FileNotFoundError:
        raise Http404('not found')
def main(request):
    return render(request,'template.html')

url.py

from django.urls import path
from django.conf.urls import url
from . import views
urlpatterns =[path('', views.main, name='main'),url(r'^pdf', views.pdf, name='pdf'),]

template.html

<embed src={% url 'pdf' %}'#toolbar=0&navpanes=0&scrollbar=0'style="width:718px; height:700px;" frameborder="0">
like image 34
Mr.Rathour Avatar answered Mar 19 '23 07:03

Mr.Rathour