如果我关注这个Question,我想你可以使用这个解决方案;
在你的views.py
from django.conf import settings
from django.shortcuts import get_object_or_404
from yourapp.models import PDF
def pdf_viewer(request, pk):
obj = get_object_or_404(PDF, pk=pk)
pdf_full_path = settings.BASE_DIR + obj.pdf.url
with open(pdf_full_path, 'r') as pdf:
response = HttpResponse(pdf.read(), content_type='application/pdf')
response['Content-Disposition'] = 'filename=%s' % obj.pdf.name
return response
pdf.closed
然后urls.py;
from django.conf.urls import url
from yourapp.views import pdf_viewer
urlpatterns = [
url(r'^pdf-viewer/(?P<pk>\d+)/$', pdf_viewer, name='pdf_viewer_page'),
]
模板里面怎么样?
<button class="show-pdf">Show PDF</button>
<div class="pdf-wrapper">
<iframe id="pdf-iframe" frameborder="0" allowfullscreen></iframe>
</div>
<script>
// you can using jQuery to load the pdf file as iframe.
$('.show-pdf').click(function () {
var src = '{% url "pdf_viewer_page" pk=obj.id %}';
var iframe = $("#pdf-iframe");
iframe.attr({'width': 560, 'height': 300});
// iframe.attr('src', src); // to load the pdf file only.
// to load and auto print the pdf file.
iframe.attr('src', src).load(function(){
document.getElementById('pdf-iframe').contentWindow.print();
});
return false;
});
</script>
但是,如果您尝试使用 {{ obj.pdf.url }},请确保在此模板中返回字符串,例如:'/media/to/file.pdf'
或者更简单(整页);
<a href='{% url "pdf_viewer_page" pk=obj.id %}' target="_blank">Show PDF on new tab</a>