📜 ⬆️ ⬇️

Use highcharts.js to create server side charts

highcharts-on-a-server
Today we will talk about using highcharts.js charts on the server side. We will write all code on C #, we will do absolutely without javascript. As a result, we get a file with a schedule that can be saved to disk or, for example, attached to a letter.

A quick search for good free .net graphics libraries was not successful. The best of all found libraries was ms-chart , but judging by the lack of updates and good documentation, Microsoft itself abandoned it long ago.

The choice fell on highcharts.js - a very flexible graphing library, which is widely used in the frontend.

Its capabilities far exceed all those libraries that exist for .net. There are two options for using highcharts.js on the server:
')

The second option was chosen, since phantom.js is not possible to run in Azure Web App ( proof ). To work with highchart-export-module, you need to raise your server (see the official manual or this blog ), but if you are too lazy to do it, you can use the server highchart.js ( http://export.highcharts.com/ ).

The highchart-export-module has a fairly simple HTTP API. In order to communicate with it from .net, a small highcharts-export-client library was written. Let's take a closer look at it.

highcharts-export-client


Like most .net libraries, install it from NuGet.

Install-Package highcharts-export-client 

To create a 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.

Basic chart

Data for the schedule can be transmitted in the form of highcharts settings. This is convenient if you use highcharts on the frontend, just copy the settings and you will get the exact same schedule on the server side.

  await client.GetChartImageFromOptionsAsync(your_highcharts_settings); 

Also, data can be transferred in svg format.

  await client.GetChartImageFromSvgAsync(svg); 

The quality and format of the resulting file can be customized by passing the HighchartsSetting object to the designer.

  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 restriction is imposed by the highchart-export-module.

The source code of the library is available on Github - highcharts-export-client .

Thanks for attention!

Source: https://habr.com/ru/post/279515/


All Articles