[Django]-Uncaught TypeError: Failed to execute 'serializeToString' on 'XMLSerializer': Failing to download an svg (created with D3.js) as png/pdf

4πŸ‘

βœ…

In your code, svg is a D3 selection. You cannot pass a D3 selection to serializeToString. Have a look at the error here:

var svg = d3.select("svg");
var svgAsXML = (new XMLSerializer).serializeToString(svg);
console.log(svgAsXML)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
  <circle r="20" cx="100" cy="50"></circle>
</svg>

As you can see, serializeToString requires a node:

The Node to use as the root of the DOM tree or subtree for which to construct an XML representation.

Therefore, instead of passing a D3 selection, you have to pass the node. The easiest way to do that is using the D3 method node() on the selection:

var svg = d3.select("svg");
var svgAsXML = (new XMLSerializer).serializeToString(svg.node());
console.log(svgAsXML)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
  <circle r="20" cx="100" cy="50"></circle>
</svg>

So, in your code, pass the node to the svgDataUrl function:

var dataURL = svgDataURL(svg.node())

Alternatively, pass the D3 selection to svgDataUrl, but use the node inside serializeToString, as I did above.

Leave a comment