4

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
Community
  • 1
  • 1
zinon
  • 4,427
  • 14
  • 70
  • 112
  • It's not clear what you are asking, you're showing a solution there yet asking the same thing? – Lorenzo Peña Oct 07 '16 at 15:31
  • 1
    If you put the document in your static folder, you should be able to call it using `{% load staticfiles %}` in your template -- `{% static 'path/to/file.pdf' %}` – jape Oct 07 '16 at 15:51
  • @LorenzoPeña Actually, this solution does not show the pdf embed in a template. It opens the pdf in a new page. I want to have it embed in a template. – zinon Oct 08 '16 at 04:55

2 Answers2

5

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?

Community
  • 1
  • 1
Lorenzo Peña
  • 2,225
  • 19
  • 35
2

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">
probitaille
  • 1,899
  • 1
  • 19
  • 37
Mr.Rathour
  • 21
  • 2