3
rob ballou Main menu Skip to content Home About Code Blog Racing Contact Post navigation Turkey Weekend Adventure Keeping context Creating an SVG file with D3 and Node.js Posted on 2013/12/20 by rballou On a recent work project, we were using the D3 library to create some graphs . But the graphs were on a page that we also needed to export to PDF and so we needed some static versions of those graphs to use with a <img> tag. At first, I thought this was going to require using a different command line library that could help generate the same file but wasn’t happy with the prospect of two separate code libraries to get the same graphing. Since we’re JavaScript to make the graphs, let’s see if we can run that graphing code with Node.js and save that output to a file. And it turns out this is fairly simple. First, we need to get Node setup with a few packages. We’ll need: d3 and xmldom. Next, we’ll take start with this example doughnut graph . So we’ll take that code and load it into a script we can use with node: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 require('d3'); var xmldom = require('xmldom'); var dataset = { apples: [53245, 28479, 19697, 24037, 40245], }; var width = 460, height = 300, radius = Math.min(width, height) / 2; var color = d3.scale.category20(); var pie = d3.layout.pie() .sort(null);

Creating an SVG File With D3 and Node

Embed Size (px)

DESCRIPTION

SVG

Citation preview

  • 2015/6/23 CreatinganSVGfilewithD3andNode.js|robballou

    http://robballou.com/2013/creatingansvgfilewithd3andnodejs/ 1/3

    robballouMainmenu

    Skiptocontent

    HomeAboutCodeBlogRacingContact

    Postnavigation

    TurkeyWeekendAdventureKeepingcontext

    CreatinganSVGfilewithD3andNode.jsPostedon2013/12/20byrballou

    Onarecentworkproject,wewereusingtheD3librarytocreatesomegraphs.ButthegraphswereonapagethatwealsoneededtoexporttoPDFandsoweneededsomestaticversionsofthosegraphstousewithatag.Atfirst,Ithoughtthiswasgoingtorequireusingadifferentcommandlinelibrarythatcouldhelpgeneratethesamefilebutwasnthappywiththeprospectoftwoseparatecodelibrariestogetthesamegraphing.

    SincewereJavaScripttomakethegraphs,letsseeifwecanrunthatgraphingcodewithNode.jsandsavethatoutputtoafile.Anditturnsoutthisisfairlysimple.

    First,weneedtogetNodesetupwithafewpackages.Wellneed:d3andxmldom.

    Next,welltakestartwiththisexampledoughnutgraph.Sowelltakethatcodeandloaditintoascriptwecanusewithnode:

    12345678910111213141516

    require('d3');varxmldom=require('xmldom');vardataset={apples:[53245,28479,19697,24037,40245],};varwidth=460,height=300,radius=Math.min(width,height)/2;varcolor=d3.scale.category20();varpie=d3.layout.pie().sort(null);

    6341http://robballou.com/2013/creating-an-svg-file-with-d3-and-node-js/

  • 2015/6/23 CreatinganSVGfilewithD3andNode.js|robballou

    http://robballou.com/2013/creatingansvgfilewithd3andnodejs/ 2/3

    viewraw

    171819202122232425262728293031

    vararc=d3.svg.arc().innerRadius(radius100).outerRadius(radius50);varsvg=d3.select("body").append("svg").attr("width",width).attr("height",height).append("g").attr("transform","translate("+width/2+","+height/2+")");varpath=svg.selectAll("path").data(pie(dataset.apples)).enter().append("path").attr("fill",function(d,i){returncolor(i);}).attr("d",arc);

    graph.jshostedwithbyGitHub

    Thiswillrunthegraphcodeforusinnodewhenwerun:nodegraph.js.Butwestillwantthissavedoutintoafile.Thisiswherexmldomcomesintoplay:

    1234567891011121314151617181920212223242526272829303132333435363738

    require('fs');require('d3');varxmldom=require('xmldom');vardataset={apples:[53245,28479,19697,24037,40245],};varwidth=460,height=300,radius=Math.min(width,height)/2;varcolor=d3.scale.category20();varpie=d3.layout.pie().sort(null);vararc=d3.svg.arc().innerRadius(radius100).outerRadius(radius50);varsvg=d3.select("body").append("svg").attr("width",width).attr("height",height).append("g").attr("transform","translate("+width/2+","+height/2+")");varpath=svg.selectAll("path").data(pie(dataset.apples)).enter().append("path").attr("fill",function(d,i){returncolor(i);}).attr("d",arc);//getareferencetoourSVGobjectandaddtheSVGNSvarsvgGraph=d3.select('svg').attr('xmlns','http://www.w3.org/2000/svg');varsvgXML=(newxmldom.XMLSerializer()).serializeToString(svgGraph[0][0]);fs.writeFile('graph.svg',svgXML);

  • 2015/6/23 CreatinganSVGfilewithD3andNode.js|robballou

    http://robballou.com/2013/creatingansvgfilewithd3andnodejs/ 3/3

    viewrawgraph.jshostedwithbyGitHub

    Thesecondscriptissimilartothefirst,butweveaddthexmldommodulesowecanserializetheobjecttoXMLandaddedfsmodulesowecansavethedatatoafile.

    Andyouredone!Well,kinda.ThiswilllikelysavetheSVGfilewithcapitalizedXMLtags,whichyouwillhavetoconverttolowercasetohaveaworkingSVGfile:http://stackoverflow.com/questions/20693235/getlowercasetagnameswithxmldomxmlserializerinnodejs/20704228

    ThisentrywaspostedinBlogandtaggedd3,javascript,node.js,programming,svg,tech,webdev.Bookmarkthepermalink.

    Postnavigation

    TurkeyWeekendAdventureKeepingcontext

    WebDevLinks

    HTML_CodeSniffer2015/06/08GenerateMozillaSecurityRecommendedWebServerConfigurationFiles2015/05/14AccessibilitytestingfromPayPal2015/05/05Mina2015/05/04jq2015/04/27

    Photos

    Servicecurrentlyunavailable(SiteDisabled)

    AboutBlogRacingContact

    Copyright2015RobBallou