DEV Community

Pelumi Oluwategbe
Pelumi Oluwategbe

Posted on

How to convert html to pdf (something like a generated invoice) and send it to an email

Long time, no post. Sorry about that, been quite busy with my youth service PPA (Place of Primary Assignment), and sadly it has taken quite so much of my time. Anyways, down to business. So I'm building this web application for my PPA which generates a delivery note from a set of inputs and sends to the inputed email by the click of the "Send Email" button. I had problems with converting it to a pdf and I did a lot of research but I finally figured it out with the help of the internet and some people at Stack Overflow (every junior developer needs help from the internet), to convert it to pdf and print by the click of a button, here's the code below:

Code to convert html to pdf

So you have to add the html2pdf script before it can work, though there are other ways, this was the one I found.
Meanwhile if you want to generate a pdf and then send it to an email, that is a different ball game. I tried fetching the downloaded pdf and then sending it to the email, but that gave me problems and I couldn't quite figure it out. Anyways, I did some research and also asked other senior developers I knew for help (Special thanks, Mr Samuel Adetoro @big_black_fella ). So I found smtpJs and followed the steps shown below

smtpJs snippets on sending attachments to email
As you can see in the highlighted part, I could send an email with attachment but the code to convert and send a pdf straight was more complex than that so I did some further research and also found some help from some guys at Stack Overflow and to avoid long talk, I had to create an Elastic email account shown below

My Elastic Email account

Then I combined it with the smtpjs code and also the html2pdf code to convert the invoice to a pdf, then change it to a datauristring and then send it as a data using the email code from smtpjs. I used elastic email as my smtp server. The code is shown below

JS code to convert html to pdf and then send as an attachment to email

Finally, it all worked out and the invoice looks like this:

The Invoice generated.
It was successfully sent to the email that was inputed. That's all from me for now, till next time. Hope you found this useful.

Top comments (1)

Collapse
 
lalami profile image
Salah Eddine Lalami

Thanks for sharing, @ IDURAR , we use are using node.js react.js & redux

Here Tutorial about : 🚀 Building and Generate Invoice PDF with React.js , Redux and Node.js : dev.to/idurar/building-an-invoice-...

 Building and Generate Invoice PDF with React.js , Redux and Node.js