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

前端 未结 2 842
粉色の甜心
粉色の甜心 2020-12-10 18:27

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         


        
相关标签:
2条回答
  • 2020-12-10 18:44

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 19:07

    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

    0 讨论(0)
提交回复
热议问题