2

如果我运行:

127.0.0.1:8000/document/1/preview

此 pdf 文件已下载。

我需要在 HTML 中显示它(带有打印功能的预览)。怎么做?

视图.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

网址.py

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

1 回答 1

5

要使文件在浏览器中打开,请使用inlinecontent-disposition。

response['Content-Disposition'] = 'inline; filename=answer_%s.pdf' % f_date
于 2013-06-05T10:32:23.530 回答