简体   繁体   中英

Printing a PDF file in Django

I want to create something in my Django project that physically prints a PDF file in the FileField of a model object onto paper. Like so:

class PDF(models.Model):
    pdf = models.FileField(upload_to='pdffiles/', blank=True, null=True}

The main thing I want to do is make a link that creates a popup using Javascript that contains an input field where the user puts the name of the PDF from the object's FileField and a button that says "Print" that triggers the physical printing function (including opening the Print Dialog Box). Am I supposed to use forms or views in order to make this function, and if I'm supposed to use Javascript to activate the printing function, how would I do it? Thanks.

EDIT: I'm thinking of using print.js. Could someone tell me how to implement print.js in my Django project? What files from the Git repository do I need to insert and how do I link them to my templates?

If I following this Question , I think you can using this solution;

In your 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

and then 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'),
]

How about inside the template?

<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>

But makesure in this template if you try with {{ obj.pdf.url }} should return string of eg: '/media/to/file.pdf'

Or more easier (full page) ;

<a href='{% url "pdf_viewer_page" pk=obj.id %}' target="_blank">Show PDF on new tab</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM