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

4

1 回答 1

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

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

于 2013-06-04T14:23:55.050 回答