[英]Printing a PDF file in Django
我想在我的Django項目中創建一些內容,以便將模型對象的FileField中的PDF文件實際打印到紙上。 像這樣:
class PDF(models.Model):
pdf = models.FileField(upload_to='pdffiles/', blank=True, null=True}
我要做的主要事情是建立一個鏈接,該鏈接使用Javascript創建一個彈出窗口,其中包含一個輸入字段,用戶在其中輸入對象的FileField中PDF的名稱,以及一個顯示“ Print”的按鈕,該按鈕觸發物理打印功能(包括打開“打印”對話框)。 我應該使用表格或視圖來實現此功能嗎?如果我要使用Javascript來激活打印功能,我該怎么做? 謝謝。
編輯:我正在考慮使用print.js。 有人可以告訴我如何在Django項目中實現print.js嗎? 我需要從Git存儲庫中插入哪些文件,如何將它們鏈接到模板?
如果我遵循此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 }}
,則此模板中的{{ obj.pdf.url }}
應該返回字符串,例如:'/media/to/file.pdf'
或更容易(整頁) ;
<a href='{% url "pdf_viewer_page" pk=obj.id %}' target="_blank">Show PDF on new tab</a>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.