1

I'm using Javascript to allow a user to export a dynamically-generated SVG element to a file. It's a rather hacky approach using Blobs and MouseEvents:

var exportSVG = function(sel) {
  var el = document.querySelector(sel);

  var blob = new Blob([el.outerHTML], {encoding:"UTF-8",type:"text/xml;charset=UTF-8"}),
      e    = document.createEvent('MouseEvents'),
      a    = document.createElement('a');

  a.download = "";
  a.href = window.URL.createObjectURL(blob);
  a.dataset.downloadurl =  ['text/xml', a.download, a.href].join(':');
  e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  a.dispatchEvent(e);
};

exportSVG("#mysvg");

The problem is that this SVG's source is on one line. Some of these one-liner SVGs have trouble rendering correctly in my browser (jumbled-up letters) - if they're pretty-printed they're fine!

So I'd like to save them with correct source formatting and indentation.

I assume I'd have to change this Blob hack because it inherently makes the source one-line. Is there something like JSON.stringify(el, null, 2) for XML?

Leeroy
  • 2,003
  • 1
  • 15
  • 21

0 Answers0