[ASP.net WebForm] 把Chart Control輸出圖片給用戶端下載
原本是想要找把Chart Control列印下來的方法
但美國MSDN的討論方法(print chart control in ASP .Net )試過不行之後
於是決定還是把Chart Control 輸出Image給用戶端下載的方式來實現
以下是懶人Sample Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Chart ID="Chart1" runat="server" >
<Series>
<asp:Series ChartArea="ChartArea1" Name="Series1">
</asp:Series>
</Series>
<ChartAreas>
<asp:ChartArea Name="ChartArea1">
</asp:ChartArea>
</ChartAreas>
</asp:Chart>
<asp:Button runat="server" ID="btn_print" OnClick="btn_print_Click" Text="print" />
</form>
</body>
</html>
Code-Behind:
//Button Click事件
protected void btn_print_Click(object sender, EventArgs e)
{
//Step 1 重新撈資料給Chart Control
Chart1.Series[0].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Column;
Chart1.ChartAreas[0].Area3DStyle.Enable3D = true;
ArrayList x = new ArrayList { "One", "Two", "Three" };
ArrayList y = new ArrayList { 1, 1, 2 };
Chart1.Series[0].Points.DataBindXY(x, y);
//Step 2.把Chart Control儲存圖片在MemoryStream
MemoryStream ms = new MemoryStream();
Chart1.SaveImage(ms);
//Step 3. Response給用戶端下載
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=test.jpg");//強制下載
Response.ContentType = "image/jpg";
Response.BinaryWrite(ms.ToArray());
ms.Close();
Response.End();
}
類似文章:[ASP.net] 取得網路上的圖片並儲存在Server和Response給用戶端下載 by 本人