[C#]
public void Export()
{
//Saving Chart as a PNG image using web browser control
System.Threading.Thread tr = new System.Threading.Thread(() => ExportChart());
tr.SetApartmentState(ApartmentState.STA);
tr.Start();
Response.Clear();
string fileName = Server.MapPath(@"\ChartExport.png");
System.IO.File.Delete(fileName);
//Make current thread wait until chart image is ready in STA thread
while(tr.IsAlive)
{
Thread.Sleep(5);
}
//Read chart image as bytes
byte[] file = System.IO.File.ReadAllBytes(fileName);
//Delete the file after reading
System.IO.File.Delete(fileName);
//Allowing client to download the image
Response.OutputStream.Write(file, 0, file.Length);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.Flush();
}
public void ExportChart()
{
//Set properties of chart in server-side
Chart _myChart = new Chart();
var prop = _myChart.Chart("Text")
.Series(sr =>
{
sr.Points(pt =>
{
pt.X("X").Y(50).Add();
}).Add();
})
.CanResize(true)
.Size(sz => sz.Height("450"))
.Size(sz => sz.Width("700"))
.Legend(lg => { lg.Visible(false); })
.PrimaryYAxis(px => px.Range(ra => ra.Min(0).Max(70).Interval(10)));
//Create web browser control
WebBrowser browser = new WebBrowser() { ScriptErrorsSuppressed=true, WebBrowserShortcutsEnabled = false, Size = new System.Drawing.Size(1000, 1000) };
//Serialize chart properties as a string
string chartOption = _myChart.Serialize(prop.chart.ChartModel);
browser.DocumentText = new StringBuilder()
//Add header for HTML document
.Append("<!DOCTYPE html><html><head><meta http-equiv='X-UA-Compatible' content='IE=edge' />"
//Add scripts required for rendering Chart in browser control
+ AddScripts(browser, chartOption)
+ "</head><body><div id='container'></div></body></html>").ToString();
//Check browser is loaded or not. If it is not ready wait until browser loading is complete
//Since this is happening in a separate thread it will not affect load time of web page
while (browser.ReadyState == WebBrowserReadyState.Loading)
{
Application.DoEvents();
Thread.Sleep(5);
}
//Get the bounds of chart in browser control
var bounds = browser.Document.InvokeScript("createChart").ToString().Split('-');
//Save chart as an image in server
using (Bitmap img = new Bitmap(ParseInt(bounds[1]), ParseInt(bounds[0])))
{
browser.DrawToBitmap(img, new Rectangle(ParseInt(bounds[2]), ParseInt(bounds[3]), img.Width, img.Height));
img.Save(Server.MapPath(@"\ChartExport.png"), ImageFormat.Png);
img.Dispose();
}
browser.Dispose();
}
|