I'm using wkhtmltopdf wrapper to generate template into PDF in Django 1.6. It works fine when I want to display the PDF afterwards or send the PDF file with HttpResponse for download but what I want to do is to create the file in my tmp folder and attach it to an email.
I'm not sure how to achieve this.
# views.py
context = {
'products_dict': products_dict,
'main_categories': main_categories,
'user_category': user_category
}
response = PDFTemplateResponse(request=request,
context=context,
template="my_template.html",
filename="filename.pdf",
show_content_in_browser=True,
cmd_options={'encoding': 'utf8',
'quiet': True,
'orientation': 'landscape',
}
)
return response
The code above generate the PDF exactly how I want it. The thing is I don't want to display the PDF in the browser or start a download (I don't want to return response). I just want to create it and then attach the file to an email like this:
email = EmailMessage()
email.subject = "subject"
email.body = "Your PDF"
email.from_email = "[email protected]"
email.to = [ "[email protected]", ]
# Attach PDF file to the email
email.attach_file(my_pdf_file_here)
# Send email
email.send()
I tried to use subprocess but it doesn't seem like I can send context to my template to render it before generating the PDF.
EDIT (SOLUTION): Thanks to Daniel Roseman for the help to go towards what I wanted. I did use the tests file of wkhtmltopdf here: http://pydoc.net/Python/django-wkhtmltopdf/1.1/wkhtmltopdf.tests.tests/
This is what I did in my view:
order = Order.objects.get(id=order_id)
return_file = "tmp/" + 'order' + str(order_id) + '.pdf'
context = {
'order' : order,
'items' : order.ordered_products.all()
}
response = PDFTemplateResponse(request=request,
context=context,
template="'products/order_pdf.html'",
cmd_options={ 'encoding': 'utf8',
'quiet': True
}
)
temp_file = response.render_to_temporary_file("products/order_pdf.html")
wkhtmltopdf(pages=[temp_file.name], output=return_file)
You can then use the return_file in email.attach() method like this:
email.attach_file(return_file)
You can also omit output parameter in the wkhtmltopdf method. Then the method will return the output and use this output in attach_file() method.