0

I have a javascript function that creates a svg in the body of the HTML page. Additionnaly to the creation of the webpage, I would like to extract the svg code generated by the javascript (the one between <svg>..</svg>) and print it in a file to be past in an other document.

For example the following html:

<html>
<head>
  <script>
    function CreateSVG () {
      var xmlns = "http://www.w3.org/2000/svg";
      var boxWidth = 300;
      var boxHeight = 300;
      var svgElem = document.createElementNS (xmlns, "svg");
      svgElem.setAttributeNS (null, "width", boxWidth);

      var g = document.createElementNS (xmlns, "g");
      svgElem.appendChild (g);
      g.setAttributeNS (null, 'transform', 'matrix(1,0,0,-1,0,300)');

      // draw borders
      var coords = "M 0, 0";
      coords += " l 0, 300";
      coords += " l 300, 0";
      coords += " l 0, -300";
      coords += " l -300, 0";

      var path = document.createElementNS (xmlns, "path");
      path.setAttributeNS (null, 'd', coords);
      g.appendChild (path);

      var svgContainer = document.getElementById ("svgContainer");
      svgContainer.appendChild (svgElem);
    }
  </script>
</head>

<body onload="CreateSVG ()">
  <div id="svgContainer"></div>
</body>
</html>

generates the following code (after being analysed by the web browser) :

<html> == $0
  <head> ... </head>
  <body onload="CreateSVG ()">
    <div id="svgContainer">
      <svg width ="300">
        <g transform="matrix(1,0,0,-1,0,300)">
          <path d="M 0, 0 1 0, 300 1 300, 0 1 0, -300 1 -300, 0"></path>
        </g>
      </svg>
    </div>
  </body>
</html>

How can I extract the <svg>...</svg> part to print it in an external file ?

ThomasGuenet
  • 183
  • 1
  • 7
  • 17

1 Answers1

0

Like Sujit Agarwal answered in https://stackoverflow.com/a/21012689/6869524, one should

save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.

And the text is retreived using code = svgContainer.innerHTML

ThomasGuenet
  • 183
  • 1
  • 7
  • 17