Skip to content Skip to sidebar Skip to footer

How To Exporting SVG As PNG Format

For the Size problem i removed some svg content. I want to achieve the svg image to be exported as png or any image format for Reporting purpose

Solution 1:

There we a few issues with your approach. I removed JQ & simplified the SVG itself. First, you need to set up what happens to the img with an onload event before you set the source. Once this is done the src has be be set with a URI, usually this is a link, but we can use

data:image/svg+xml;base64

So here's a version which will log to console your <svg> as .png(in base64).

<html>
 <head>
  <script>
   window.onload = function() {  
    var myCanvas = document.getElementById('myCanvas');
    var myCanvasContext = myCanvas.getContext('2d');
    var source = new Image();
    var img = document.getElementById('svg1');
    source.onload = function() {
     myCanvasContext.drawImage(source,0,0,200,200);
     document.getElementById('output').src = myCanvas.toDataURL("image/png");
     console.log(myCanvas.toDataURL("image/png"));
    }     
    source.src = 'data:image/svg+xml;base64,'+btoa(img.outerHTML);
   }
  </script>
  </script>
 </head>
 <body>
  <h1>My first SVG</h1>
  <canvas id="myCanvas" width="200" height="100"></canvas>
  <svg version="1.1" id="svg1" xmlns="http://www.w3.org/2000/svg" width="322" height="194">
   <text x="49" text-anchor="end" transform="translate(0,0)" y="76" opacity="1">50</text>
   <text x="49" text-anchor="end" transform="translate(0,0)" y="13" opacity="1">100</text>
  </svg>
  <img id="output" />
  <input type="button" onclick="SaveasImage()" value="exportasimage" />
 </body>
</html>

Post a Comment for "How To Exporting SVG As PNG Format"