Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export complete d3 tree graph as png or pdf

Tags:

svg

d3.js

I have a Zoom-able, dragable, tree graph which has thousands of nodes using inside my angular application.

Design referenced from here.

I can download/export SVG or any parent div of SVG from my d3 graph.

The issue is that only SVG elements can be downloaded which do not contain complete tree graphs because SVG gets overflow by its inner element "g". SVG has a inner group element "g" which is bigger than SVG's height and width, and it is dynamic (drag-able).

This "g" element has a complete tree graph that I am not able to export as image or pdf.

How do I export a complete graph?

like image 849
shashi keshari Avatar asked Oct 13 '25 05:10

shashi keshari


1 Answers

If you're exporting an SVG file:

  1. clone your original SVG node
  2. append it to the document, so it has the bounding box calculated
  3. clean the transform from the parent g node, where you're translating and scaling
  4. set the cloned SVG with its width and height with the content bounding box dimension
  5. serialize the SVG and download it as a document

You might need to add inline styles to SVG so it's rendered properly outside the original d3 application.

Example:

  const svg = document.querySelector('svg').cloneNode(true); // clone your original svg
  document.body.appendChild(svg); // append element to document
  const g = svg.querySelector('g') // select the parent g
  g.setAttribute('transform', '') // clean transform
  svg.setAttribute('width', g.getBBox().width) // set svg to be the g dimensions
  svg.setAttribute('height', g.getBBox().height)
  const svgAsXML = (new XMLSerializer).serializeToString(svg);
  const svgData = `data:image/svg+xml,${encodeURIComponent(svgAsXML)}`
  const link = document.createElement("a");
  document.body.appendChild(link); 
  link.setAttribute("href", svgData);
  link.setAttribute("download", "image.svg");
  link.click();

How to export the SVG from canvas. http://bl.ocks.org/curran/7cf9967028259ea032e8

like image 169
calmar Avatar answered Oct 14 '25 20:10

calmar