0

您将如何生成表单值的临时 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,
    })
4

1 回答 1

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()
于 2013-01-14T14:47:38.727 回答