简体   繁体   English

如何使用asp.net c将使用jsPDF生成的PDF附加到邮件中

[英]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#? 我需要知道是否有任何方法可以附加使用jsPDF生成的PDF文件并将其邮寄到asp.net C#中?

I have the following code in c# 我在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: 我正在使用JsPDF库,如下所示:

<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. 提前致谢。

You cannot call client-side code (Javascript function) from server code (c#). 您无法从服务器代码(c#)调用客户端代码(Javascript函数)。 You can only communicate via the (HTTP/HTTPs) protocol. 您只能通过(HTTP / HTTPs)协议进行通信。

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. 我认为您需要从客户端生成PDF,然后将该PDF发送到服务器,以便您可以将PDF附加到电子邮件中。

In that case you need to first generate the PDF and send it to the server as a base64 string. 在这种情况下,您需要首先生成PDF并将其作为base64字符串发送到服务器。

You can then convert the base64 string to PDF in C# and mail it as an attachment. 然后,您可以将base64字符串转换为C#中的PDF并将其作为附件邮寄。

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: base64 pdf内容发布到服务器:

  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): 在服务器上(MVC控制器):

        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 有关更多信息,请访问此处https://github.com/Purush0th/PDFnMail

Your code example use pdf.text() , but in most situations, you want to export a html page with table(s) or image(s). 您的代码示例使用pdf.text() ,但在大多数情况下,您希望导出带有表格或图像的html页面。 The latest version jsPDF html PlugIn instead of addHtml() . 最新版本jsPDF html PlugIn而不是addHtml() Below is an code example using jsPDF html() and Web API. 下面是使用jsPDF html()和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; 请注意,从datauristring返回的pdf.html具有添加到字符串的filename=generated.pdf;filename=generated.pdf; . Also, SmtpClient is obsolete , consider to use MailKit instead. 此外,SmtpClient已过时 ,请考虑使用MailKit

[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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM