Django表单:将生成的pdf从表单值附加到电子邮件

时间:2013-01-14 09:52:29

标签: django pdf django-forms

您如何生成表单值的临时pdf并将其附加到电子邮件中?你是在form_view中做到的吗?

def show_orderform(request):
    if request.method == 'POST':

        form = OrderForm(request.POST)

        if form.is_valid():
            subject = "New order"

            email = form.cleaned_data['email']

            recipients = ['orders@domain.com']

            rendered = render_to_string('emailtemplates/email_body.html', {'form':form , 'form_headline':subject})

            msg = EmailMultiAlternatives(subject, rendered, email, recipients)
            msg.attach_alternative(rendered, "text/html")
            msg.send()            
            return HttpResponseRedirect('/order/completed/')


    else:
        form = OrderForm() # An unbound form

    return render(request, 'forms/orderform.html', {
        'form': form,
    })

1 个答案:

答案 0 :(得分:1)

我们使用pisa生成我们的pdf。您可以在form.is_valid()和将pdf附加到电子邮件之间的某个地方执行此操作。

这三个函数已添加到我们的代码库中,因此我们可以从任何地方生成pdf。

import os
import StringIO
import xhtml2pdf.pisa as pisa

def fetch_resources(uri, rel):
    """
    Callback to allow xhtml2pdf/reportlab to retrieve Images,Stylesheets, etc.
    `uri` is the href attribute from the html link element.
    `rel` gives a relative path, but it's not used here.
    """
    if uri.startswith(settings.MEDIA_URL):
        path = os.path.join(settings.MEDIA_ROOT,
            uri.replace(settings.MEDIA_URL, ""))
    elif uri.startswith(settings.STATIC_URL):
        path = os.path.join(settings.STATIC_ROOT,
            uri.replace(settings.STATIC_URL, ""))
    else:
        path = os.path.join(settings.STATIC_ROOT,
            uri.replace(settings.STATIC_URL, ""))

        if not os.path.isfile(path):
            path = os.path.join(settings.MEDIA_ROOT,
                uri.replace(settings.MEDIA_URL, ""))

            if not os.path.isfile(path):
                raise Exception(
                    'media urls must start with %s or %s' % (
                        settings.MEDIA_ROOT, settings.STATIC_ROOT))

    return path


def render_to_pdf(template_src, context_dict):
    """Function to render html template into a pdf file"""
    template = get_template(template_src)
    context = Context(context_dict)
    html = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),
        dest=result,
        encoding='UTF-8',
        link_callback=fetch_resources)
    if not pdf.err:
        response = HttpResponse(result.getvalue(), mimetype='application/pdf')
        return response

    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))


def write_pdf(template_src, context_dict, filename):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = open(filename, 'wb') # Changed from file to filename
    pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result)
    result.close()