2

I have the code shown below (taken from here) that creates a bar chart:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.chart div {
  font: 10px sans-serif;
  background-color: steelblue;
  text-align: right;
  padding: 3px;
  margin: 1px;
  color: white;
}

</style>
<div class="chart"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var data = [4, 8, 15, 16, 23, 42];

var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, 420]);

d3.select(".chart")
  .selectAll("div")
    .data(data)
  .enter().append("div")
    .style("width", function(d) { return x(d) + "px"; })
    .text(function(d) { return d; });

</script>

I want to add a download as pdf button/link just under my plot, that provides a pdf of the plot. I have seen for example some posts, like this, or even this but they do not seem that they provide a simple and fast solution to address this problem. Do you know a simple way to do that? How can I convert my plot as pdf and provide a link to that?

Community
  • 1
  • 1
Jim Blum
  • 2,656
  • 5
  • 28
  • 37

1 Answers1

3

I don't have enough rep to flag as a duplicate, but a very similar question is asked here: Export SVG elements to PDF?

I think the closest you could get for your use case is to offer an export of the SVG element's contents as a file. If you go down that road, make sure you apply all of the stuff you have in the block of your html inside the d3 code. E.g.

d3.select(".chart").style("font", "10px sans-serif");

otherwise it will get lost.

In case its relevant, my solution for getting PDFs out of d3 is to run an element extraction script with phantomjs for the SVG, save it as an SVG file and then convert that to PNG and PDF with Python (Cairo library). Some details are here (technical stuff half way down): http://mattf.surmise.co.uk/2013/06/14/using-d3js-and-revealjs-for-better-organised-data-presentation/. But that is obviously not very helpful for a simple client side development.

The following web service lets you download a page screenshot as PNG. If you generated a page with the figure only on it (i.e. on the server) and put a link to the service with the figure-only link, you could at least have download as PNG.

http://webshot.okfnlabs.org/?url=http://www.google.com&width=640&height=480

Community
  • 1
  • 1
Matt Fullerton
  • 535
  • 3
  • 8