Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save inline SVG as JPEG/PNG/SVG

I have an inline SVG in my html, and I need to be able to save this as either a JPEG, PNG or SVG.

I have tried a few different methods with converting the SVG to canvas and then converting to JPEG, but I haven't been able to get these working.

Here is an example of my inline SVG.

.font {  	color: #ffffff;  	font-family: Roboto;  	font-weight: bold;  	text-transform: uppercase;  }  .name {  	font-size: 64pt;  }  .top-bar-text {  	font-size: 32pt;  }  .font tspan {  	dominant-baseline: middle;  }
<link href='http://fonts.googleapis.com/css?family=Roboto:700' rel='stylesheet' type='text/css'>    <svg width="256" height="256" id="icon">    <rect class="bg1" id="bg_color_1" x="0" y="0" width="256" height="256" fill="#4cbc5a" />    <path class="bg2" id="bg_color_2" d="M 0 96 L0,256 L256,256 L256,96 s -128 96 -256 0" fill="#08a21c" />    <text id="left_corner_text" x="24" y="36" width="48" height="64" class="top_bar lct font top-bar-text" text-anchor="middle" fill="#ffffff"><tspan>1</tspan></text>    <text id="right_corner_text" x="232" y="36" width="48" height="64" class="top_bar rct font top-bar-text" text-anchor="middle" fill="#ffffff"><tspan>2</tspan></text>    <text id="line_1_text" transform="scale(1,2)" x="128" y="90" width="256" height="192" class="l1t font name" text-anchor="middle" fill="#ffffff"><tspan>ABC</tspan></text>  </svg>

Also, not all the elements need to be exported, as some of the options the user has is to remove the top corner numbers.

I would like for when it's been converted to download straight to the browser.

like image 217
Tim Rideyourbike Avatar asked Jan 29 '15 23:01

Tim Rideyourbike


People also ask

Can you save an SVG as a PNG?

Navigate to an . svg file, right click on it and click on the context menu item 'Save SVG as PNG. Lets you click on the extension icon or right click on an . svg file and choose Save SVG as PNG.

How do you convert an SVG to a JPEG?

Go to File. Select Export. Click Export As. Select JPG format from the drop-down menu.

How can I save SVG code as a .SVG image?

You can use the Save As feature to save to the SVG format directly. Choose File > Save As from the Menu Bar. You can create a file and then choose File > Save As to save the file. In the save window, change the Format to SVG (svg) and then click Save.

How do I convert a SVG file?

How to convert a SVG to a PNG file? Choose the SVG file that you want to convert. Select PNG as the the format you want to convert your SVG file to. Click "Convert" to convert your SVG file.


2 Answers

Nowadays this is pretty simple.

The basic idea is:

  1. SVG to canvas
  2. canvas to dataUrl
  3. trigger download from dataUrl

it actually works outside of the Stack Overflow snippet

var btn = document.querySelector('button'); var svg = document.querySelector('svg'); var canvas = document.querySelector('canvas');  function triggerDownload (imgURI) {   var evt = new MouseEvent('click', {     view: window,     bubbles: false,     cancelable: true   });    var a = document.createElement('a');   a.setAttribute('download', 'MY_COOL_IMAGE.png');   a.setAttribute('href', imgURI);   a.setAttribute('target', '_blank');    a.dispatchEvent(evt); }  btn.addEventListener('click', function () {   var canvas = document.getElementById('canvas');   var ctx = canvas.getContext('2d');   var data = (new XMLSerializer()).serializeToString(svg);   var DOMURL = window.URL || window.webkitURL || window;    var img = new Image();   var svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});   var url = DOMURL.createObjectURL(svgBlob);    img.onload = function () {     ctx.drawImage(img, 0, 0);     DOMURL.revokeObjectURL(url);      var imgURI = canvas         .toDataURL('image/png')         .replace('image/png', 'image/octet-stream');      triggerDownload(imgURI);   };    img.src = url; });
<button>svg to png</button>  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="200" height="200">   <rect x="10" y="10" width="50" height="50" />   <text x="0" y="100">Look, i'm cool</text> </svg>  <canvas id="canvas"></canvas>

Regarding the downloading part, you can set up a filename and etc etc (although not in this example). Some days ago I answered a question on how to download a specific portion of HTML from the given page. It might be useful regarding the downloading part: https://stackoverflow.com/a/28087280/2178180

update: now letting you specify the filename

like image 153
Ciro Costa Avatar answered Oct 24 '22 19:10

Ciro Costa


Here's a solution that works in IE11 as well.

I just did a bunch of testing of various methods of this and while the above answer by Ciro Costa is fantastic in that it works in Firefox and Chrome it does not work in IE11. IE11 fails due to a security issue with rendering an svg to the canvas which requires a canvas implementation, canvg. Here's a solution using canvg that's pretty terse and works in the latest versions of Chrome, Firefox, Edge, and IE11.

Fiddle: https://jsfiddle.net/StefanValentin/9mudw0ts/

DOM

<svg   id="my-svg"   xmlns="http://www.w3.org/2000/svg"   xmlns:xlink="http://www.w3.org/1999/xlink"   version="1.1"   width="200"   height="200" >   <rect x="10" y="10" width="50" height="50" />   <text x="0" y="100">Look, i'm cool</text> </svg> 

JavaScript

var svg = document.querySelector('#my-svg'); var data = (new XMLSerializer()).serializeToString(svg); // We can just create a canvas element inline so you don't even need one on the DOM. Cool! var canvas = document.createElement('canvas'); canvg(canvas, data, {   renderCallback: function() {     canvas.toBlob(function(blob) {         download('MyImageName.png', blob);     });   } }); 

The download function above could be whatever you want to do, as there are many ways to trigger a download via JavaScript. Here's the one we use that works in all the browsers I've tested.

// Initiate download of blob function download(   filename, // string   blob // Blob ) {   if (window.navigator.msSaveOrOpenBlob) {     window.navigator.msSaveBlob(blob, filename);   } else {     const elem = window.document.createElement('a');     elem.href = window.URL.createObjectURL(blob);     elem.download = filename;     document.body.appendChild(elem);     elem.click();     document.body.removeChild(elem);   } } 
like image 36
KhalilRavanna Avatar answered Oct 24 '22 18:10

KhalilRavanna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!