d3js is a JavaScript library for manipulating documents based on data. The library enables stunning client-side visualization inside the webbrowser.

Commonly in science-related websites (and possibly many others), users need to save the generated visualization in vectorized format (e.g. PDF), to be able to incorporate the graphics in presentation or publications.

This website demonstate one possible method of saving d3js graphics to PDF.

See below for more technical details.

d3js drawing

Export Drawing

SVG Code:

Technical details

This demo was developed by gordon@cshl.edu.

Data flow

  • Use d3js to generate graphics, on an HTML5 SVG element
    (client-side, see create_d3js_drawing() function in this HTML file.).
  • Use XMLSerializer.serializeToString() to extract the SVG/XML structure of the d3js drawing
    (client-side, see show_svg_code() function in this HTML file).
  • The SVG/XML data is submitted to the server's CGI script, which converts it to PDF/PNG and sends it back to the user as an attachment file to download
    (server side, see Perl script).

Future improvements

  • Saving files directly from the browser: not properly supported by all browsers, perhaps use FileSaver.js library
  • Generating PDF on the client side: Create an adaptation layer between d3js and jsPDF library.

The following libraries were used

Source Code

  • The client-side code (HTML/CSS/Javascript) is contained in a single file (which you're seeing now). Click "view source" to see it. It is heavily documented.
  • The server-side code is a bare-bones Perl/CGI script.. It basically runs rsvg-convert and returns the result as an attachment to download. You can implement the same functionallity in any programming language.
  • The entire code is available on GitHub, so fork me.