Export SVG file using XMLSerializer

Scenario

I was considering how I can export SVG as a file using client JavaScript. The way I found on the Internet uses XMLSerializer and create a element for download. Let’s see how it goes.

2016-06-01_104845

DEMO SOURCE

Solution

About

We are going to use native JavaScript only; hence, you don’t need any library but the browser compatibility of XMLSerializer must be confirmed.

2016-06-01_095625

It seems work on most modern browsers. :p

Create SVG Sample Element

  <svg xmlns="http://www.w3.org/2000/svg" id="svg-01" width="600" height="250">
    <rect fill="none" stroke="#000" stroke-width="1" x="0" y="0" width="600" height="250" />
    <text class="item-title" style="font-size: 30px; font-weight: 900;" lengthAdjust="spacing" textLength="480" x="60" y="40">Export SVG using XMLSerializer</text>
  </svg>

Download Function

We are going to create a element for download method. The element within attributes:

  • download: This is the name of download file.
  • href: This is the content of download file.
    function generateLink(fileName, data) {
      var link = document.createElement('a'); // Create a element.
      link.download = fileName; // Set value as the file name of download file.
      link.href = data; // Set value as the file content of download file.
      return link;
    }

Begin To Export!

New a XMLSerializer object and serial our SVG element to a string. Then, we have to prepend ‘data:image/svg+xml;utf8,’ for Data URIs. .click() will fire as user click.

    function exportSVG(element, fileName) {
      var svg = element;
      var svgString;
      if (window.ActiveXObject) {
        svgString = svg.xml;
      } else {
        var oSerializer = new XMLSerializer();
        svgString = oSerializer.serializeToString(svg);
      }
      generateLink(fileName + '.svg', 'data:image/svg+xml;utf8,' + svgString).click();
    }

Click & Download

.onclick binds the function on the element.

    document.getElementById('downloadBtn').onclick = function() {
      var element = document.getElementById('svg-01');
      exportSVG(element, 'SVG-01');
    }
Advertisements

Author: jsgao0

My name is Jia-Siang Gao. Or call me Anson. At present, I'm a full-stack web developer in Kinpo Group. I love to sovle problems of technology.

One thought on “Export SVG file using XMLSerializer”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s