将JSPDF pdf文件作为电子邮件附件发送

时间:2017-07-03 08:27:59

标签: java email jspdf html2canvas

我在客户端使用JSPdf创建了PDF文件。我需要使用java将pdf附加到电子邮件中。此过程需要在服务器端完成。有没有办法做到这一点。我的代码如下

$('#export').click(function () {
            $('#officeUse').hide();
            $("#customerdata2clone").html($("#customerdata2").html());
            $('#customerdata2').hide();
            $('#customerdata3').show();
            var imgData2;
            var imgData3;
            setTimeout(function(){html2canvas($("#customerdata2clone"), {
                 onrendered: function(canvas) {         
                     imgData2 = canvas.toDataURL(
                         'image/jpeg');              

                 }
             });}, 1000);
             setTimeout(function(){ html2canvas($("#customerdata3"), {
                 onrendered: function(canvas) {         
                     imgData3 = canvas.toDataURL(
                         'image/jpeg');              

                 }
             });}, 2000);
             setTimeout(function(){ html2canvas($("#customerdata"), {
                 onrendered: function(canvas) {         
                     var imgData = canvas.toDataURL(
                         'image/jpeg');              
                     var doc = new jsPDF("p", "px", "a4");
                     doc.context2d.pageWrapYEnabled = true;
                     var width = doc.internal.pageSize.width;    
                     var height = doc.internal.pageSize.height;
                     var pageHeight= doc.internal.pageSize.height;
                     doc.addImage(imgData, 'JPEG', 5, 5, width-10, height-10);
                     doc.addPage();
                     doc.addImage(imgData2, 'JPEG', 5, 5,width-10, height-10);
                     doc.addPage();
                     doc.addImage(imgData3, 'JPEG', 5, 5,width-10, height-405); 
                     doc.save($("#tFullName").html()+'_'+strDate+'.pdf');

                     $('#customerdata2').show();
                     $('#officeUse').show();
                     $('#focus').focus();
                     $("#customerdata3").hide();
                     $("#customerdata2clone").html('');
                 }
             }); }, 3000);

        });

在服务器端,我需要获取PDF文件。

2 个答案:

答案 0 :(得分:1)

您可以将jsPdf转换为base64格式,它可以发送到后端 在角度6中,代码将为

ts文件

      var pdfBase64 = pdf.output('datauristring');

相应的服务将

  sendMail(file: any, supplier_email: any,supplier:any) {
const body={
  file:file,
  supplier:supplier_email,
  supplier_name:supplier
}
return this.http.post(this.url.baseUrl+'/purchaseOrder/sendMail? 
      access_token='+this.token.value,body,{responseType:'text'});

}

在后端(这里我正在使用Java

     String b64;
     byte[] decoder = null;
    JSONObject obj=new JSONObject(json);
    String str=obj.getString("file");
    String email=obj.getString("supplier");
    String name=obj.getString("supplier_name");
    List<String> data = Arrays.asList(str.split(","));
    String ss=data.get(1);
    File file = new File("./test.pdf");

        try ( FileOutputStream fos = new FileOutputStream(file); ) {
          // To be short I use a corrupted PDF string, so make sure to use a valid one 
        if you want to preview the PDF file
           b64 = obj.getString("file");
           decoder = Base64.getDecoder().decode(ss);

          fos.write(decoder);
        } catch (Exception e) {
          e.printStackTrace();
        }
      

如果您想邮寄以上pdf文件,请使用以下邮编

       final String user="mmm@gmail.com";//change accordingly  
      final String password="mmmme";//change accordingly  
       
      //1) get the session object     
      Properties props = System.getProperties();  
      props.put("mail.smtp.host", "smtp.gmail.com");    
         props.put("mail.smtp.socketFactory.port", "465");    
         props.put("mail.smtp.socketFactory.class",    
                   "javax.net.ssl.SSLSocketFactory");    
         props.put("mail.smtp.auth", "true");    
         props.put("mail.smtp.port", "465");  
      
      Session session = Session.getDefaultInstance(props,  
       new javax.mail.Authenticator() {  
       protected PasswordAuthentication getPasswordAuthentication() {  
       return new PasswordAuthentication(user,password);  
       }  
      });  
         
      //2) compose message     
      try{  
        MimeMessage message = new MimeMessage(session);  
        message.setFrom(new InternetAddress(user));  
        message.addRecipient(Message.RecipientType.TO,new InternetAddress(email));  
        message.setSubject("Purchase Order List");  
          
        //3) create MimeBodyPart object and set your message text     
        BodyPart messageBodyPart1 = new MimeBodyPart();  
        string msg="hvgfj";
        messageBodyPart1.setContent(msg,"text/html"); 
        
        MimeBodyPart mbp = new MimeBodyPart();
      //            byte[] data1 =decoder;
        DataSource ds = new ByteArrayDataSource(decoder, "application/pdf");
        mbp.setDataHandler(new DataHandler(ds));
          
        //4) create new MimeBodyPart object and set DataHandler object to this object      
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();  
      
  //5) create Multipart object and add MimeBodyPart objects to this object      
        Multipart multipart = new MimeMultipart();  
        multipart.addBodyPart(messageBodyPart1);  
        multipart.addBodyPart(mbp); 
 //         System.out.println("multi part data"+multipart);
        
       
      
        //6) set the multiplart object to the message object  
        message.setContent(multipart );  
         
        //7) send message  
        Transport.send(message);  
       
       System.out.println("message sent....");  
       }catch (MessagingException ex) {ex.printStackTrace();}

答案 1 :(得分:0)

解决方法是首先创建 datauristring 并发送到服务器。在服务器端,解码相同的uri并作为附件发送。我使用java作为服务器端编程。有关附件发送邮件,请参阅下面的链接,
Java codes for sending mail with attachment

if(attach){
    var pdfBase64 = doc.output('datauristring');
    $.post('sendEmailPrescriptionPdf', {attach: pdfBase64,filename: jsonResponse.pdfdata.tokenNo,email_id: jsonResponse.pdfdata.patientEmail}, function(jsonResponse) {});
    }
else{   
    doc.save(jsonResponse.pdfdata.tokenNo+'_Prescription.pdf');
    }