简体   繁体   中英

Sending JSPDF pdf file as Email attachment

I have created the PDF file using JSPdf in client side. I need to attach the pdf in email using java. This process need to be done in Server side. Is there any possible way to do this. My code is follows

$('#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);

        });

In server side i need to get the PDF file.

You can convert the jsPdf into base64 format, it can send to the back end in angular 6 ,the code will be

ts file

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

Corresponding service will be

  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'});

}

in Back end(here i am using 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();
        }
      

if you want to mail the above pdf ,use below mail code

       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();}

The solution to this, is to first create datauristring and send to server. At the server end, decode the the same uri and send as attachment. I have used java as serverside side programming. See bellow link for Sending mails with attachments,
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');
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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