django:将比萨生成的pdf附加到电子邮件中

时间:2013-10-28 08:48:22

标签: django pdf email-attachments pisa

我正在试图弄清楚如何将pisa生成的pdf附加到电子邮件中。早些时候,我能够使用缓冲区制作附件,但那是我使用直接reportlab的时候。我无法弄清楚如何将这个概念应用于转换后的pdf

这就是你使用reportlab的方法:

def pdfgenerate(request):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename="invoicex.pdf"'

    buffer = BytesIO()

    # Create the PDF object, using the BytesIO object as its "file."
    p = canvas.Canvas(buffer)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(100, 100, "Hello world.")

    # Close the PDF object cleanly.
    p.showPage()
    p.save()

    # Get the value of the BytesIO buffer and write it to the response.
    pdf = buffer.getvalue()
    buffer.close()

    email = EmailMessage('Hello', 'Body', 'from@from.com', ['to@to.com'])
    email.attach('invoicex.pdf', pdf , 'application/pdf')
    email.send()
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

这是我到目前为止使用的代码,比萨生成的pdf:

def render_to_pdf(request, 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:
        response = HttpResponse(result.getvalue(), mimetype='application/pdf')
        response['Content-Disposition'] = 'filename="invoicex.pdf"'
        email = EmailMessage('Hello', 'Body', 'from@from.com', ['to@to.com'])
        email.attach('invoicex.pdf', pdf , 'application/pdf')
        email.send()
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

def labelsend(request, order_id):
    labels = LabelOrder.objects.get(LabelOrderID=order_id)
    args = {}

    args['labels'] =labels

    return render_to_pdf(request, 'labelsforprint.html', args)

1 个答案:

答案 0 :(得分:2)

你需要result.getvalue() 不是pdf

email.attach('invoicex.pdf', result.getvalue() , 'application/pdf')