20

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.

Pankaj
  • 1,221
  • 2
  • 14
  • 20
  • 5
    Possible duplicate of [How to convert/save d3.js graph to pdf/jpeg](http://stackoverflow.com/questions/16049538/how-to-convert-save-d3-js-graph-to-pdf-jpeg) – Cyril Cherian Mar 30 '16 at 08:56

2 Answers2

21

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.

Jaimin Patel
  • 371
  • 2
  • 8
  • 4
    I am using this library but I cannot access my external css files. Is there any way to access them or any way to pass my css classes to the library so that my image is rendered properly. – anchal20 Nov 22 '18 at 10:27
  • I know the last answer is very old, but did you find a solution for this problem? – capek Jul 14 '20 at 17:01
4

SaveSvgAsPng worked for me too. But if you want it to work in IE, you need to include "canvg" and pass it as parameter as below:

function saveAsImage(name, id) {

var svg = $('#'+id).find('svg')[0];

saveSvgAsPng(svg, name + '.png', { canvg: canvg, backgroundColor: 'white'});

}

"backgroundColor" parameter is also useful when your graphs need to be saved with a background.