2013-10-28 93 views
0

我想弄清楚如何得到由比薩生成的PDF附加到電子郵件。早些時候,我能夠使用緩衝區來創建附件,但是那時我正在使用直接的reportlab。我無法弄清楚如何將這一概念應用到轉換的PDFdjango:附pisa生成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', '[email protected]', ['[email protected]']) 
    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', '[email protected]', ['[email protected]']) 
     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

你需要result.getvalue() 不PDF

email.attach('invoicex.pdf', result.getvalue() , 'application/pdf') 
相關問題