Home .NET Using highcharts.jsto create server-side graphs

Using highcharts.jsto create server-side graphs

by admin

Using highcharts.jsto create server-side graphs
Today we’re going to talk about using highcharts.js charts on the server side.All code will be written in C#, we’ll do without javascript at all. As a result we’ll get a file with a chart, which you can save to your disk or attach to an email, for example.
A quick search for good free .net libraries for creating graphs was unsuccessful. The best of all the libraries I found was ms-chart but judging by the lack of updates and good documentation Microsoft itself abandoned it long ago.
I chose highcharts.js – a very flexible library for graphing, which is widely used on the frontend.
Its capabilities far surpass all those libraries that exist for .net. There are two ways to use highcharts.js on the :

The second option was chosen because phantom.js cannot be run in the Azure Web App ( proof ).To work with the highchart-export-module, you need to get your server up (see official guide or this blog ), but if you’re too lazy to do it, you can use the highchart.js server ( http://export.highcharts.com/ ).
The highchart-export-module has a pretty simple HTTP API. In order to communicate with it from .net a small library called highcharts-export-clientwas written. Let’s take a closer look at it.

highcharts-export-client

Like most .net libraries, let’s install it from NuGet.

Install-Package highcharts-export-client

To create the graph, use the 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);

The result of the code is shown in the image below.
Using highcharts.jsto create server-side graphs
The data for the chart can be passed in the form of highcharts settings. This is useful if you use highcharts on the frontend, just copy the settings and you will get exactly the same graph on the server side.

await client.GetChartImageFromOptionsAsync(your_highcharts_settings);

You can also transfer data in svg format.

await client.GetChartImageFromSvgAsync(svg);

You can adjust the quality and format of the resulting file by passing the HighchartsSetting object to the constructor.

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. The maximum file resolution is 2000px – this limit is imposed by the highchart-export-module.
The source code of the library is available on Github – highcharts-export-client
Thank you for your attention!

You may also like