javascriptc#asp.netjspdf

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.


Solution

  • 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