Using highchart.js On a Server-Side

highcharts-on-a-server

Today we'll talk about highcharts.js usage on a server. Forget about javascript, all code will be written in C#. In the end of article, we'll get a static chart image, which we can attach to email or save somewhere.

Quick googling for good .net charting libraries has not give any reasonable results. The best what I found is ms-chart. But it lacks good documentation and updates, it seems like Microsoft just abandoned it.

My choice is highcharts.js: very powerful and flexible library, widely used in front-end development. You just can't compare highcharts with whatever .net charting libraries. They sucks!

Highcharts charts can be rendered on server in two different ways:

I have selected second way, because it's impossible to run local phantomjs server on Azure Web App (proof). Highchart-export-module requires standalone server (see official docs or this post). If you lazy you can use highcharts export server (http://export.highcharts.com/).

Highchart-export-module has a very simple HTTP API, to work with it we'll use a highcharts-export-client library.

highcharts-export-client

Install it from NuGet.

Install-Package highcharts-export-client

To create a sample chart use following code:

var client = new HighchartsClient("http://export.highcharts.com/");

var options = new  
{
    xAxis = new
    {
      categories = new[] { "Jan", "Feb", "Mar" }
    },
    series = new[]
    {
      new { data = new[] {29.9, 71.5, 106.4} }
    }
};

var res = await client.GetChartImageFromOptionsAsync(JsonConvert.SerializeObject(options));

File.WriteAllBytes("image.png", res);  

Sample chart placed below.

Sample chart

Chart data can be passed either in highcharts setting format or as svg. With highcharts settings format you can get exactly the same chart as on frontend. It's really nice feature as for me.

// highchart settings
await client.GetChartImageFromOptionsAsync(your_highcharts_settings);

// svg
await client.GetChartImageFromSvgAsync(svg);  

Resolution and format of a result image file can be changed.

var settings = new HighchartsSetting  
{
  ExportImageType = "jpg",         
  ImageWidth = 1500,
  ServerAddress = "http://export.highcharts.com/"
};

var client = new HighchartsClient(settings);  

Supported formats are png, jpg, pdf and svg. Maximum image resolution is 2000px due to highchart-export-module limits.

If you know any other ways to use highcharts on backend, share your thoughts in comments.

Github repository: highcharts-export-client.