Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you download a image/png data URI in Edge?

I am trying to export an SVG created in the browser (a d3.js chart) as a PNG using methods based from https://github.com/exupero/saveSvgAsPng and http://techslides.com/save-svg-as-an-image. The SVG is converted to a data URI and rendered as an image in a canvas, which is converted to a PNG data URI. This URI is downloaded as a file using an anchor tag. I have been able to confirm this to work in current versions of FF, Chrome, and Safari; however, triggering the download on the anchor tag causes Edge to either hang (with only a doctype warning in the console) or crash completely. Is there anyway to get this to work in Edge or is the anchor download with data URI not fully supported yet?

Code created from the sources above:

//this gets the svg and inlines all styles.  It has a property "source" as well as width and height of the SVG.
var svgDownload = getElementChildrenAndStyles(svgID);

var image = new Image();

image.onload = function () {
  var canvas = document.createElement('canvas');
  canvas.width = svgDownload.width;
  canvas.height = svgDownload.height;
  var ctx = canvas.getContext('2d');
  ctx.fillStyle = "#FFFFFF";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(image, 0, 0);

  var a = document.createElement("a");
  a.download = "chart.png";
  try {
    console.log("converting canvas");
    a.href = canvas.toDataURL("image/png");
    console.log("canvas converted. triggering download");
    document.body.appendChild(a);
    a.addEventListener("click", function(e) {
      a.parentNode.removeChild(a);
    });
    a.click();
  }
  catch (e){
    //error handling
  }

};
try {
  console.log("making image source url");
  //both methods of creating the image source here work in most browsers except Edge
  //image.src = "data:image/svg+xml;base64," + btoa( svgDownload.source.join() );
  image.src = window.URL.createObjectURL(new Blob(svgDownload.source, {"type": 'image/svg+xml;base64'}));
  console.log("image source set");
}
catch (e){
  //error handling
}
like image 888
asharon.mori Avatar asked Oct 19 '22 09:10

asharon.mori


1 Answers

Realise this is an old question but for others that end up here: Edge and IE don't support dataURL as the href of an anchor tag. It will accept it as the source of an img tag though. The best solution I've been able to come up with is to use download.js to download the file. However, the next problem you will hit is when you set the src of an image tag to SVG to do the rendering of the PNG, the "load" event won't fire in Edge for that Image object. Haven't got a way around that just yet.

like image 177
rstuart85 Avatar answered Oct 21 '22 04:10

rstuart85