django-xhtml2pdf - 生成pdf(编解码器不能解码字节)

时间:2013-06-04 12:36:34

标签: django

def preview_pdf(request, did):
    d_instance = get_object_or_404(MyObject, pk=did, user=request.user)
    #resp = HttpResponse(content_type='application/pdf')
    result = generate_pdf('pdf_preview.html')

    return render_to_response('pdf_preview.html', {'objects': d_instance,'result':result}, RequestContext(request))

pdf_preview.html:

{{result}}

<iframe src="http://docs.google.com/viewer?url={{result}}.pdf&embedded=true" width="600" height="780" style="border: none;"></iframe>

{{objects.name}}

但不显示文档。

{{result}}显示为:<StringIO.StringIO instance at 0xb4da030c>

1 个答案:

答案 0 :(得分:2)

我认为你需要设置编解码器参数,用于PDF中的编码内容 你需要这样的东西:

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

您可以将此创建的文档加载到另一个框架中。