JavaScript to download a SVG as a PNG image (for printing etc.)

JavaScript to download a SVG as a PNG image (for printing etc.)

This can be a simple way to allow a user to print out or email the SVG ...

//JavaScript: (works in Chrome)
 var exportSvgToPng = function(svgDivElem){  
   let width = svgDivElem.getBoundingClientRect().width;  
   let height = svgDivElem.getBoundingClientRect().height;  
   let svg = svgDivElem;  
   let svg_xml = (new XMLSerializer()).serializeToString(svg),  
     blob = new Blob([svg_xml], {type:'image/svg+xml;charset=utf-8'}),  
     url = window.URL.createObjectURL(blob);  
   let img = new Image();  
   img.width = width;  
   img.height = height;  
   let canvas = this.lowCanvas.nativeElement;  
   let a = this.lowLink.nativeElement;  
   img.onload = function(){  
     canvas.width = width;  
     canvas.height = height;  
     let context = canvas.getContext('2d');  
     context.drawImage(img, 0, 0, width, height);  
     window.URL.revokeObjectURL(url);  
     var canvasdata = canvas.toDataURL('image/png');  
     a.download = 'svgToPng_' + Date.now() + '.png';  
     a.href = canvasdata;  
   }  
   img.src = url;  
 };  


//HTML

{svg id="svg1"}{/svg}


//usage - JavaScript code:
 exportSvgToPng(document.getElementById('svg1'));  


Comments