2016-02-17 41 views
2

我需要知道是否有任何方式附加使用jsPDF生成的PDF文件並將其發送到asp.net C#中?如何將使用jsPDF生成的PDF附加到使用asp.net的郵件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); 

和我使用的是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> 

有沒有什麼辦法將其附加在郵件發送前呢? 在此先感謝。

+0

那麼,你有JsPDF運行在客戶端上,並且你的電子郵件代碼在服務器上運行。所以你必須得到由JsPDF生成的PDF並傳遞給服務器。 – mason

+0

你知道如何將它傳遞給服務器嗎? –

+0

所有常用的方式.....提交表單...通過AJAX ....通過WebSockets ...等。或者您可以放棄在客戶端上生成PDF的想法,而是在服務器上生成PDF。 – mason

回答

1

您不能從服務器代碼(c#)調用客戶端代碼(Javascript函數)。 您只能通過(HTTP/HTTPs)協議進行通信。

我認爲您需要從客戶端生成PDF,然後將該PDF發送到服務器,以便您可以將PDF附加到電子郵件。

在這種情況下,您需要先生成PDF並將其作爲base64字符串發送到服務器。

然後,您可以將C#中的base64字符串轉換爲PDF並將其作爲附件郵寄。

客戶端:

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

} 

公示的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(){} 
     }); 

在服務器(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; 
} 

檢查在這裏獲取更多信息https://github.com/Purush0th/PDFnMail

相關問題