Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to attach a PDF generated using jsPDF to the mail using asp.net c#

I need to know if there is any way to attach a PDF file generated using jsPDF and mail it in asp.net C#?

I have the following code in c#

MailMessage message = new MailMessage(fromAddress, toAddress);
        message.Subject = subject;
        message.IsBodyHtml = true;
        message.Body = StrContent.ToString();
        //message.Attachments.Add(new Attachment("getDPF()"));
        smtp.Send(message);

and I'm using a JsPDF library as follows:

<script type="text/javascript" src="jsPdf/jspdf.min.js"></script>
<script type="text/javascript">
    function getPDF()
    {
        var doc = new jsPDF();
        doc.text(20, 20, 'TEST Message');
        doc.addPage();
        //doc.save('volt.pdf');
    }
</script>

Is there any way to attach it in the mail before send it? Thanks in advance.

like image 838
Rodolfo Lanshore Avatar asked Feb 17 '16 18:02

Rodolfo Lanshore


2 Answers

You cannot call client-side code (Javascript function) from server code (c#). You can only communicate via the (HTTP/HTTPs) protocol.

I think you need to generate the PDF from the client and then send that PDF to server so that you can attach the PDF to an email.

In that case you need to first generate the PDF and send it to the server as a base64 string.

You can then convert the base64 string to PDF in C# and mail it as an attachment.

Client Side:

function generatePdf() {    
    var doc = new jsPdf();
    doc.text("jsPDF to Mail", 40, 30);    
    var binary = doc.output();
    return binary ? btoa(binary) : "";

}

Posting the base64 pdf content to the server:

  var reqData = generatePdf();
$.ajax({
                url:url,
                data: JSON.stringify({data:reqData}),
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success:function(){}
       });

On the server (MVC Controller):

        public ActionResult YourMethod(string data)
        {
            //create pdf
            var pdfBinary = Convert.FromBase64String(data);
            var dir = Server.MapPath("~/DataDump");

            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            var fileName = dir + "\\PDFnMail-" + DateTime.Now.ToString("yyyyMMdd-HHMMss") + ".pdf";

            // write content to the pdf
            using (var fs = new FileStream(fileName, FileMode.Create))
            using (var writer = new BinaryWriter(fs))
            {
                writer.Write(pdfBinary, 0, pdfBinary.Length);
                writer.Close();
            }
            //Mail the pdf and delete it
            // .... call mail method here 
           return null; 
}

Check out here for more information https://github.com/Purush0th/PDFnMail

like image 119
Purushoth Avatar answered Nov 04 '22 08:11

Purushoth


Your code example use pdf.text(), but in most situations, you want to export a html page with table(s) or image(s). The latest version jsPDF html PlugIn instead of addHtml(). Below is an code example using jsPDF html() and Web API.

Client side:

function emailHtml() {
    let pdf = new jsPDF('p', 'pt', 'a3'); // a4: part of the page is cut off?
    pdf.html(document.body, {
        callback: function (pdf) {
            let obj = {};
            obj.pdfContent = pdf.output('datauristring');
            var jsonData = JSON.stringify(obj);
            $.ajax({
                url: '/api/jspdf/html2pdf',
                type: 'POST',
                contentType: 'application/json',
                data: jsonData
            });
        }
    });
}

Note that the datauristring returned from pdf.html has a filename added to the string, filename=generated.pdf;. Also, SmtpClient is obsolete, consider to use MailKit instead.

[Route("[action]")]
[HttpPost]
public void Html2Pdf([FromBody] JObject jObject)
{
    dynamic obj = jObject;
    try
    {
        string strJson = obj.pdfContent;
        var match = Regex.Match(strJson, @"data:application/pdf;filename=generated.pdf;base64,(?<data>.+)");
        var base64Data = match.Groups["data"].Value;
        var binData = Convert.FromBase64String(base64Data);

        using (var memoryStream = new MemoryStream())
        {
            var mail = new MailMessage
            {
                From = new MailAddress("[FromEmail]")
            };
            mail.To.Add("");
            mail.Subject = "";
            mail.Body = "attached";
            mail.IsBodyHtml = true;
            mail.Attachments.Add(new Attachment(new MemoryStream(binData), "htmlToPdf.pdf"));

            var SmtpServer = new SmtpClient("[smtp]")
            {
                Port = 25,
                Credentials = new NetworkCredential("[FromEmail]", "password"),
                EnableSsl = true
            };

            SmtpServer.Send(mail);
        }
    }
    catch (Exception ex)
    {
        throw;
    }
}
like image 1
Weihui Guo Avatar answered Nov 04 '22 07:11

Weihui Guo