Export a D3 chart

Fusionexport doesn't confine you to FusionCharts - you can also export charts generated by using D3.js . In this tutorial, you will learn how to use FusionExport for exporting a chart created using D3.js.

Prerequisites

Before starting with the code, ensure that you have:

  1. Downloaded and installed FusionExport Server , and the server is running

  2. Downloaded and installed the FusionExport SDK client

Chart Template

FusionExport needs a HTML file containing the code for the D3 chart. For this tutorial, we will assume that the file is located at the following path:

<export_code_executed_from_this_directory>/resources/d3chart.html

We will consider this chord diagram as an example. The minimal .html file necessary for this chart is:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style>
        body {
            font: 10px sans-serif;
        }

        .chord {
            fill-opacity: .67;
        }
    </style>
</head>
<body>
    <script src=" https://d3js.org/d3.v3.min.js"></script>
    <script>
        var outerRadius = 1366 / 2,
            innerRadius = outerRadius - 130;
        var fill = d3.scale.category20c();
        var chord = d3.layout.chord()
            .padding(.04)
            .sortSubgroups(d3.descending)
            .sortChords(d3.descending);
        var arc = d3.svg.arc()
            .innerRadius(innerRadius)
            .outerRadius(innerRadius + 20);
        var svg = d3.select("body").append("svg")
            .attr("width", outerRadius * 2)
            .attr("height", outerRadius * 2)
            .append("g")
            .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")");
        d3.json(
            " https://gist.githubusercontent.com/sandeep1995/141a2045ab9e4c8f450c970682b89b00/raw/7aacb8a793c2d9e0ed60ad0251e1b754b2c430f2/filename.json",
            function(error, imports) {
                if (error) throw error;
                var indexByName = d3.map(),
                    nameByIndex = d3.map(),
                    matrix = [],
                    n = 0;
                // Returns the Flare package name for the given class name.
                function name(name) {
                    return name.substring(0, name.lastIndexOf(".")).substring(6);
                }
                // Compute a unique index for each package name.
                imports.forEach(function(d) {
                    if (!indexByName.has(d = name(d.name))) {
                        nameByIndex.set(n, d);
                        indexByName.set(d, n++);
                    }
                });
                // Construct a square matrix counting package imports.
                imports.forEach(function(d) {
                    var source = indexByName.get(name(d.name)),
                        row = matrix[source];
                    if (!row) {
                        row = matrix[source] = [];
                        for (var i = -1; ++i < n;) row[i] = 0;
                    }
                    d.imports.forEach(function(d) {
                        row[indexByName.get(name(d))]++;
                    });
                });
                chord.matrix(matrix);
                var g = svg.selectAll(".group")
                    .data(chord.groups)
                    .enter().append("g")
                    .attr("class", "group");
                g.append("path")
                    .style("fill", function(d) {
                        return fill(d.index);
                    })
                    .style("stroke", function(d) {
                        return fill(d.index);
                    })
                    .attr("d", arc);
                g.append("text")
                    .each(function(d) {
                        d.angle = (d.startAngle + d.endAngle) / 2;
                    })
                    .attr("dy", ".35em")
                    .attr("transform", function(d) {
                        return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")" +
                            "translate(" + (innerRadius + 26) + ")" +
                            (d.angle > Math.PI ? "rotate(180)" : "");
                    })
                    .style("text-anchor", function(d) {
                        return d.angle > Math.PI ? "end" : null;
                    })
                    .text(function(d) {
                        return nameByIndex.get(d.index);
                    });
                svg.selectAll(".chord")
                    .data(chord.chords)
                    .enter().append("path")
                    .attr("class", "chord")
                    .style("stroke", function(d) {
                        return d3.rgb(fill(d.source.index)).darker();
                    })
                    .style("fill", function(d) {
                        return fill(d.source.index);
                    })
                    .attr("d", d3.svg.chord().radius(innerRadius));
                // Emitting CAPTURE_EXIT event after d3 chart render complete
                FusionExport.emit('CAPTURE_EXIT');
            });
        d3.select(self.frameElement).style("height", outerRadius * 2 + "px");
    </script>
</body>
</html>

Code

Before you start with the code, we suggest going through the steps that the code accomplishes.

  1. Import and resolve the dependencies as per the system/programming language specific dependencies, and the FusionExport SDK client.

  2. Create a new instance of the ExportConfig() object, and use its set() method to pass the path of the HTML file containing the D3 chart, and to set the asyncCapture flag to true.

  3. Create a new instance of the ExportManager() object. To export the chart, pass the instance of ExportConfig() to export(), which is a method of the instance of ExportManager(). This will export the chart, and save the output file to the path you provide (by default, it is the directory from which the code is being executed).

  4. Optionally, you can print the names of the exported files on the console, and the error messages if anything goes wrong.

The above guidelines may vary slightly based on the programming language you are using, and the customizations you want on top of the defaults.

The exported dashboard will have the default name of export--1.png. If you execute the template code without any changes, you can find it in the same directory from where the code has been executed.

For detailed information on the vast number of possibilities, refer to FusionExport SDK API Reference , and select the SDK of your choice from the left navigation panel.


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using FusionCharts.FusionExport.Client; // Import sdk

namespace FusionExportTest
{
    public static class D3_Exp
    {
        public static void Run(string host = Constants.DEFAULT_HOST, int port = Constants.DEFAULT_PORT)
        {
            // Instantiate the ExportConfig class and add the required configurations
            ExportConfig exportConfig = new ExportConfig();
            List results = new List();

            // Instantiate the ExportManager class
            using (ExportManager exportManager = new ExportManager())
            {
                // Pass the path of the D3 charts’s html file
                exportConfig.Set("templateFilePath", "./resources/d3chart.html");

                /
                Setting the asyncCapture flag to true tells FusionExport to wait for all the JavaScript of the D3 chart to do their magic
                /
exportConfig.Set("asyncCapture", true); // Call the Export() method with the export config results.AddRange(exportManager.Export(exportConfig, outputDir = ".", unzip = true)); } foreach (string path in results) { Console.WriteLine(path); } Console.Read(); } } }

import com.fusioncharts.fusionexport.client.; // import sdk

public class Script {
    public static void main(String[] args) throws Exception {
        String configPath = "resources/chart-config-file.json";

        // Instantiate the ExportConfig class and add the required configurations
        ExportConfig config = new ExportConfig();

        // Pass the path of the D3 chart’s html file
        config.set("templateFilePath", "./resources/d3chart.html");

        /
        Setting the asyncCapture flag to true tells FusionExport to wait for all the JavaScript of the D3 chart to do their magic
        */
        config.set("asyncCapture", true);

        // Instantiate the ExportManager class
        ExportManager manager = new ExportManager();
        // Call the export() method with the export config and the respective callbacks
        manager.export(config, outputDir = ".", unzip = true);
    }
}

<?php

  // Import dependencies
  require DIR__ . '/../vendor/autoload.php';
  use FusionExport\ExportManager;
  use FusionExport\ExportConfig;

  // Instantiate the ExportConfig class and add the required configurations
  $exportConfig = new ExportConfig();

  // Pass the path of the D3 chart’s html file
  $exportConfig->set('templateFilePath', realpath('resources/dashboard-template.html'));

  /
  Setting the asyncCapture flag to true tells FusionExport to wait for all the JavaScript of the D3 chart to do their magic
  /
  $exportConfig->set('asyncCapture', true);

  // Instantiate the ExportManager class
  $exportManager = new ExportManager();

  // Call the export() method with the exportConfig and the respective callbacks
  $exportManager->export($exportConfig, $outputDir = '.', $unzip = true);

?>

// ** IMPORT AND RESOLVE DEPENDENCIES ***

// Import 'path' core module of Node.js
const path = require('path');

// Import FusionExport SDK client for Node.js
const {
    ExportManager,
    ExportConfig
} = require('fusionexport-node-client');

// ** EXPORT CONFIG ***

// Instantiate ExportConfig and add the required configurations
const exportConfig = new ExportConfig();


// Pass the path of the html file containing the code for the d3.js chart
exportConfig.set('templateFilePath', path.join(__dirname, 'resources', 'd3chart.html'));

/
Setting the asyncCapture flag to true tells FusionExport to wait
for all the JavaScript of the D3 chart to do their magic
/
exportConfig.set('asyncCapture', true);

// ** EXPORT-MANAGER ***

// Instantiate ExportManager
const exportManager = new ExportManager();

// * OUTPUT **

// Provide the exportConfig
// Optionally, print the exported file names and error messages, if any

exportManager.export(exportConfig, outputDir = '.', unzip = true).then((exportedFiles) => {
    exportedFiles.forEach(file => console.log(file));
}).catch((err) => {
    console.log(err);
});

# Import sdk
from fusionexport import ExportManager, ExportConfig 

# Instantiate the ExportConfig class and add the required configurations
export_config = ExportConfig()

# Pass the path of the html file containing the code for the d3.js chart
export_config["templateFilePath"] = "resources/d3chart.html"

# Setting the asyncCapture flag to true tells FusionExport to wait
# for all the JavaScript of the D3 chart to do their magic
export_config["asyncCapture"] = "true"

# Provide port and host of FusionExport Service
export_server_host = "127.0.0.1"
export_server_port = 1337

# Instantiate the ExportManager class
em = ExportManager(export_server_host, export_server_port)

# Call the export() method with the export_config as an argument
em.export(export_config, outputDir = ".", unzip = True)
Was this article helpful to you ?