Hello,
How can I save a chart, which is rendered in the view page, as an image file on the SERVER side?
For example, when I click a button, how the following chart can be saved as an image file on the SERVER (NOT on the client side, NOT to be downloaded as a image file by the user)?
<ejs-chart id="contaner">
<e-chart-primaryxaxis valueType="DateTime" labelFormat="MMM yy" intervalType="Months "></e-chart-primaryxaxis>
<e-chart-primaryyaxis valueType="Double" labelFormat="##.## kg"></e-chart-primaryyaxis>
<e-series-collection>
<e-series dataSource="ViewBag.Data" xName="Date" width="2" opacity="1" yName="Weight" type="@Syncfusion.EJ2.Charts.ChartSeriesType.Line">
<e-series-marker visible="true" height="10" width="10"></e-series-marker>
</e-series>
</e-series-collection>
</ejs-chart>
I am really shocked this feature is NOT documented anywhere. I believe, in earlier versions of Syncfusion, this was available, for example: https://www.syncfusion.com/kb/10256/how-to-export-the-chart-as-an-image-png-format-without-displaying-ui
But the above code no longer works with EJ2.
So, can you please provide an updated code sample?
Thank you in advance,
Hi Dimitris,
Greetings from Syncfusion.
We request you to use ajax call to pass the image string URL from view to controller page. Then, you can convert the passed base64 string to bytes and save an image in required location. Please check with below code snippet.
|
Index.cshtml <ejs-chart id="container"></ejs-chart> <script> function myFunction() { var chart = document.getElementById("container").ej2_instances[0]; var element = document.createElement("canvas"); element.setAttribute("id", "ej2-canvas"); element.setAttribute("width", "1000"); element.setAttribute("height", "500"); var url = window.URL.createObjectURL(new Blob([(new XMLSerializer()).serializeToString(chart.svgObject)], { type: 'image/svg+xml' })); var image = new Image(); var ctx = element.getContext('2d'); image.onload = (function () { ctx.drawImage(image, 0, 0); callAjaxFunction(element.toDataURL()); }); image.src = url; function callAjaxFunction(img) { $.ajax({ type: "POST", url: './Create', data: '{"data":"' + img + '"}', dataType: "json", contentType: "application/json;charset=utf-8", success: function (data) { }, error: function (args) { } }); } } </script> HomeController.cs [HttpPost] public ActionResult Create(string data ) { string x = data.Replace("data:image/png;base64,", ""); // Convert Base64 String to byte[] byte[] imageBytes = Convert.FromBase64String(x); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); // Convert byte[] to Image ms.Write(imageBytes, 0, imageBytes.Length); System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true); image.Save(Server.MapPath("~/App_Data/img.png"), System.Drawing.Imaging.ImageFormat.Png); return Json(data); } |
Please revert us if you have any concerns.
Regards,
Durga Gopalakrishnan.