Search code examples
pythondjangopdfwkhtmltopdf

Any way to create PDF file with wkhtmltopdf without returning HttpResponse or using URL? I just want to attach PDF file to email


I am 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 am 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.


Solution

  • Your issue is not with wkhtmltopdf, but the django-wkhtmltopdf which provides some class-based views that it renders with wkhtmltopdf. If you don't want a view, you don't need to use them: you could just render the template yourself and pass the result string to the command-line wkhtmltopdf tool.

    It looks like the django-wkhtmltopdf library does provide some utility functions (in the utils directory) which might make that last stage a bit easier.