Zee
Zee

Reputation: 874

How do I save an svg node to a file using nodejs?

I'm using d3 through a small helper package: https://www.npmjs.com/package/d3-node

I created my svg file using d3-node, here's the code.

const D3Node = require('d3-node')

var d3n = new D3Node()
var svg = d3n.createSVG()
    .style("width","1920px")
    .style("height","1080px") 
    .attr("preserveAspectRatio","true")
.html(firstTemplate)
.append("myCustomTag")

Now after this, I have no idea how to save the output. The main problem is in myCustomTag.

console.log(d3n.d3Element.select("svg").node().innerHTML)

This line is supposed to output my svg, and it does, except that myCustomTag becomes mycustomtagand my svg gets corrupt.

I have tried select("svg").node().outerHTML, select("svg").html(), innerText, I just couldn't find anything.

I can't use the innerHTML in this case, is there a way to store the svg file directly from the d3 variable?

Upvotes: 3

Views: 3197

Answers (1)

Robert Longson
Robert Longson

Reputation: 124249

You could use xmlserializer since SVG is XML and XML is case sensitive. Something like this works for me:

const D3Node = require('d3-node');
const xmlserializer = require('xmlserializer');

const d3n = new D3Node();
var svg = d3n.createSVG()
    .style("width","1920px")
    .style("height","1080px")
    .attr("preserveAspectRatio","true");

svg.append("myCustomTag");

console.log(xmlserializer.serializeToString(svg.node()));

HTML is not case sensitive so when you try to use HTML methods to serialize things you won't necessarily get what you want.

Upvotes: 8

Related Questions