user2426362
user2426362

Reputation: 309

Preview PDF document

If I run:

127.0.0.1:8000/document/1/preview

this pdf file is downloaded.

I need display it in HTML(preview with print function). How to do it?

views.py

from xhtml2pdf import pisa
from django.template.loader import render_to_string
from datetime import datetime
import StringIO

def pdf_report(request, did):
    d_instance = get_object_or_404(MyObject, pk=did, user=request.user)

    contents = render_to_string('pdf_preview.html', {'object':d_instance})
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=answer_%s.pdf' % (f_date,)
    result = StringIO.StringIO()
    pdf = pisa.pisaDocument(StringIO.StringIO(contents.encode('utf-8')), result, show_error_as_pdf=True, encoding='UTF-8')
    if not pdf.err:
        response.write(result.getvalue())
        result.close()
        return response

urls.py

(r'^document/(?P<did>\d+)/preview/$', 'app.views.pdf_report'),

Upvotes: 2

Views: 1923

Answers (1)

Thomas
Thomas

Reputation: 11888

To make the file open in the browser, use inline content-disposition.

response['Content-Disposition'] = 'inline; filename=answer_%s.pdf' % f_date

Upvotes: 5

Related Questions