0
votes

i have a variable which contain the template code like

template = '''
<html>
<div>
Hello world
</div>
</html>
'''

i want to generate a pdf and attach file with the sendgrid code below

import os
from sendgrid import SendGridAPIClient


template = '''
<html>
<div>
Hello world
</div>
</html>

message = {
    'personalizations': [
        {
            'to': [
                {
                    'email': '[email protected]'
                }
            ],
            'subject': 'Sending with Twilio SendGrid is Fun'
        }
    ],
    'from': {
        'email': '[email protected]'
    },
    'content': [
        {
            'type': 'text/plain',
            'value': template
        }
    ]
}
try:
    sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(str(e))

currently i have created a template of invoice and now i want to know how to generate a pdf with that template and attach that pdf file with the email

my template code is too lengthy so im not including it here

1
these are 2 different questions (i) how to convert html to pdf (several solutions, e.g. pypi.org/project/xhtml2pdf), and (ii) adding attachments to sendgrid messages (sendgrid has excellent docs, if you've tried e.g. github.com/sendgrid/sendgrid-python/blob/master/use_cases/… you should say so...)thebjorn

1 Answers

0
votes

I use PDKFIT to do something similar you are looking to achieve

I create HTML files as templates and then iterate through them and convert to PDF

pdfkit is "offline" (it doesnt make use of an online conversion API) which was very important to me from a data security POV

import pdfkit
import os

files = os.listdir('generated/')

options = {'disable-javascript': None}

for file in files:

       convert = str('generated/' + file)
       converted = str('upload/' + file + ".pdf")
       pdfkit.from_file(convert, converted, options=options)

       os.remove('generated/' + file)
       print(file + " deleted!")