Home > Net >  SVG download results in file with "invalid SVG Code"
SVG download results in file with "invalid SVG Code"

Time:10-23

I am building a site where people can customize SVG color and then download it so that they have illustrations that match their brand colors (without using an art program). Right now I am trying to implement the download feature so that when a user clicks the icon, it downloads the SVG to their computer.

I have the following code from browsing other topics:

$('.item-download-icon').on('click', function() {
    let imageToDownload = $(this).parent().siblings('.item-code').find('svg');
    var svg_data = imageToDownload[0].innerHTML;
    console.log(svg_data);
    var head = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 800 800" style="enable-background:new 0 0 800 800;" xml:space="preserve">'
    var full_svg = head   svg_data   "</svg>"
    var blob = new Blob([full_svg], {type: "image/svg xml"});  
    saveAs(blob, "test.svg");
    //console.log(imageToDownload);
});

It uses FileSaver.js library. However, when I download the file I get "SVG invalid" error when trying to open with illustrator. When I drag it into Chrome is says:

error on line 11 at column 430: Namespace prefix inkscape for current-layer on namedview is not defined

Any thoughts on what I'm doing wrong? Thanks! Text of the full SVG is here: https://docs.google.com/document/d/19gOZ7NGjSDP4VrEPgpRuc4Di_4IffuKglkXB4YYGbcU/edit?usp=sharing

Thanks!

CodePudding user response:

Your SVG contains attributes specific to Inkscape, but you haven't defined the inkscape namespace (http://www.inkscape.org/namespaces/inkscape).

Including it in your root element will probably fix this, although you might have other missing namespaces like sodipodi (http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd):

var head = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 800 800" style="enable-background:new 0 0 800 800;" xml:space="preserve">'

You can also opt clean up your source SVG to remove all elements and attributes belonging to these namespaces, but this will limit your ability to further edit the SVG in Inkscape or other software.

  • Related