Skip to content Skip to sidebar Skip to footer

Convert HTML Div To Image In JQuery

I want to pass an url from my jsp page. It should parse that page, fetch a specific div of html and convert div output in to a image and display it on my page. Example: I pass www.

Solution 1:

@Pushkar Sharan you can do this with html2canvas just add some script like jquery-ui.css, jquery.js, jquery-ui.js, https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js then try to understand below code

<html>
    <head>
      <link href="jquery-ui.css" >
      <script src="jquery.js"></script>
      <script src="jquery-ui.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
      <script>
          $(window).load(function(){
           $('#load').click(function(){ //calling this function when Save button pressed
              html2canvas($('#cont'), {//give the div id whose image you want in my case this is #cont
              onrendered: function (canvas) {
              var img = canvas.toDataURL("image/png",1.0);//here set the image extension and now image data is in var img that will send by our ajax call to our api or server site page


              $.ajax({
                    type: 'POST',
                    url: "http://localhost/my/index.php",//path to send this image data to the server site api or file where we will get this data and convert it into a file by base64
                    data:{
                      "img":img
                    },
                    success:function(data){
                    $("#dis").html(data);
                    }
              });
              }
              });
          });
        });
      </script> 
    </head>
    <body>
      <div id="cont"> 

      </div><br>
      <center><input type="button" value="Save" id="load"></center><br>
      <div id="dis"></div>
    </body>
</html>

Now server site program suppose this is index.php so

index.php

    <?php
    $img = $_POST['img'];//getting post img data
            $img = substr(explode(";",$img)[1], 7);//converting the data 
            $target=time().'img.png';//making file name
            file_put_contents('uploads/'.$target, base64_decode($img));//converting the $img with base64 and putting the image data in uploads/$target file name  
//now just check in your upload folder you will get your html div image in that folder
    ?>

Post a Comment for "Convert HTML Div To Image In JQuery"