简体   繁体   中英

Django: change pdf file name using pisa reportlab

I have a Django application which prints out a pdf file. I would like to know how to change the pdf file output name. Here is my views.

def write_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), mimetype='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=Client_Summary.pdf'
        return response
    return HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html))


def client_summary_pdf(request, client_id):
    client = models.Client.objects.get(pk = client_id)
    items = client.storageitem_set.all()
    return write_pdf('client_summary.html',{
        'pagesize' : 'A4',
        'client':client,
        'items':items})

As you can see, I have tried saying response['Content-Disposition'] = 'attachment; filename=Client_Summary.pdf' response['Content-Disposition'] = 'attachment; filename=Client_Summary.pdf' , but this does not work. It basically opens/saves the pdf file without a name.

You have a bug in your code because you return a bit too early:

if not pdf.err:
    response = HttpResponse(result.getvalue(), mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=Client_Summary.pdf'
    return response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM