user2426362
user2426362

Reputation: 309

django-xhtml2pdf - Generate pdf (codec can't decode byte)

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

but does not display the document.

{{result}} is displayed like: <StringIO.StringIO instance at 0xb4da030c>

Upvotes: 0

Views: 1187

Answers (1)

nnmware
nnmware

Reputation: 950

I think you need set codec parameter, for encode content in PDF You need something like this:

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

And you may load this created document in another frame.

Upvotes: 2

Related Questions