Search code examples
javascriptsvgbase64xml-serialization

Encode svg image to base64 in javascript


I have to encode svg images to base64 strings (for use in jsPDF). I found this question which povides a way to do it using an svg element that's already in the DOM. But my svg images are in a folder on my server, and should not be displayed in the DOM.

Is there a way I can use this syntax

var s = new XMLSerializer().serializeToString(something)

with an external image file (say, 'images/picture.svg') ?


Solution

  • You could use JQuery to do that for example:

    $.get("/my/nice/url/image.svg", function(data) {
      var s = new XMLSerializer().serializeToString(data.documentElement)
      console.log(s)
      ...
    });