Tola
Tola

Reputation: 264

How to convert svg string to svg file using Python?

Using AJAX I send a svg image to Django using the following function:

function uploadSVG(){

    var svgImage = document.getElementById("SVG");

    var serializer = new XMLSerializer();
    var svgStr = serializer.serializeToString(svgImage);

    $(document).ready(function(){
        $.post("ajax_upload_svg/",
      {
        csrfmiddlewaretoken: csrftoken,
        svgImage: svgStr
      },
      function(){
        console.log('Done')
      });
    });
}

In Django I end up with the svg image as a string using the following function:

def uploadSVG(request):

    svgImg = request.POST.get('svgImage')

    return HttpResponse('')

The string I get looks like this:

<svg xmlns="http://www.w3.org/2000/svg" id="SVG" width="460" height="300" style="border:2px solid #000000"><rect x="150" y="70" width="160" height="130" fill="#292b2c"/></svg>

How can I convert this svg string into a svg file?

Upvotes: 1

Views: 1429

Answers (1)

Tola
Tola

Reputation: 264

The solution is:

with open("svgTest.svg", "w") as svg_file:
        svg_file.write(svgImg)

Upvotes: 2

Related Questions