Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save D3 chart as image

Tags:

d3.js

I created lots of D3 chart in the application .

But right now my requirement is to save D3 chart in any format like png/gif or pdf.

I searched a lot and every one say we can use canvas for that.

Can anyone give any example or link for that...

Conceptually I am clear about that like

Use the canvg JavaScript library to render the SVG image using Canvas: https://github.com/gabelerner/canvg

Capture a data URI encoded as a JPG (or PNG) from the Canvas, according to these instructions: Capture HTML Canvas as gif/jpg/png/pdf?

What I want actually if any one have implemented, then could you please share the code.

like image 549
Pankaj Avatar asked Mar 30 '16 08:03

Pankaj


1 Answers

After searching many resources and trying many things, I found SaveSvgAsPng on GitHub.

It's very easy to implement and to use with resources available on README page on the same link.

Steps

  1. Add Javascript library to your project.
  2. Write a function with saveSvgAsPng call, include other options as required.

Example usage

saveSvgAsPng(document.getElementsByTagName("svg")[0], "plot.png");

Example function using d3.js

// I have button in html with id="download"
d3.select("#download")
.on('click', function(){
    // Get the d3js SVG element and save using saveSvgAsPng.js
    saveSvgAsPng(document.getElementsByTagName("svg")[0], "plot.png", {scale: 2, backgroundColor: "#FFFFFF"});
})

For this example, my plots are small for a web page so increased size to double for download and rather than transparent background as default I changed to white.

like image 189
Jaimin Patel Avatar answered Nov 10 '22 02:11

Jaimin Patel