Run Highcharts on Server side code to add to Word

2019-08-19 02:54发布

问题:

I am using Highcharts on an ASP.Net MVC Project. All works great on client side/js however I have a requirement to create a word document via the project that includes one of these charts you can see on screen.

I currently use Novacode's docx library to create/modify word files and this works great. I can add images easily and if necessary I can create the basic looking charts with .Nets charting library but I'd prefer to use the Highcharts ones.

Does anyone know how via a Controller (i.e. server side) I can create a Highcharts chart or get the image for one to use in the document. The only examples I can find still require some level of JS to accomplish it.

回答1:

I have resolved this myself in the end using the following:

HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://export.highcharts.com");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        HttpResponseMessage response = client.PostAsync("", content).Result;
        if (response.IsSuccessStatusCode)
        {
            FileStream fileStream = new FileStream(pathname, FileMode.Create, FileAccess.Write, FileShare.None);
            response.Content.CopyToAsync(fileStream).ContinueWith(
               (copyTask) =>
               {
                   fileStream.Close();
               });
        }
        else
        {
            Console.WriteLine($"Failed to poste data. Status code:{response.StatusCode}");
        }

The json for it I constructed via the options here: https://www.highcharts.com/docs/export-module/export-module-overview

Apologies for the crude example which I will obviously modify and clean up my end but wanted to give the answer to this should anyone else find it useful.