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

前端 未结 2 849
粉色の甜心
粉色の甜心 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,(?.+)");
            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;
        }
    }
    

提交回复
热议问题