首页 > 代码库 > 在asp.net中如何自己编写highcharts图表导出到自己的服务器上来

在asp.net中如何自己编写highcharts图表导出到自己的服务器上来

1.准备工作:
网上下载highcharts导出的关键dll。
      1)、Svg.dll:因为highcharts的格式其实就是一个xml,采用svg的方式画图;
      2)、itextsharp.dll:这样主要是用于处理和提取highcharts图表内的文字以及编码问题;

2.创建一个简单asp.net项目,并把上述两个程序集引入到项目中,OK。
3.给出页面代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HCExport.aspx.cs" Inherits="HighCharts_Web.HCExport" ValidateRequest="false"  %><!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>    <script type="text/javascript" src=http://www.mamicode.com/"Scripts/highcharts/jquery-1.8.3.min.js"></script>    <script type="text/javascript" src=http://www.mamicode.com/"Scripts/highcharts/highcharts.js"></script>    <script type="text/javascript" src=http://www.mamicode.com/"Scripts/highcharts/exporting.js"></script>    <script type="text/javascript">        var chart;        $(function () {            $(document).ready(function () {                chart = new Highcharts.Chart({                    chart: {                        renderTo: container,                        plotBackgroundColor: null,                        plotBorderWidth: null,                        plotShadow: false                    },                    title: {                        text: Browser market shares at a specific website, 2010                    },                    tooltip: {                        pointFormat: {series.name}: <b>{point.percentage}%</b>,                        percentageDecimals: 1                    },                    plotOptions: {                        pie: {                            allowPointSelect: true,                            cursor: pointer,                            dataLabels: {                                enabled: true,                                color: #000000,                                connectorColor: #000000,                                formatter: function () {                                    return <b> + this.point.name + </b>:  + this.percentage +  %;                                }                            },                            showInLegend: true //是否显示图例                        }                    },                    exporting: {                        filename: mychart,                        url: "/HCExport.aspx"                    },                    series: [{                        type: pie,                        name: Browser share,                        data: [                    [Firefox, 45.0],                    [IE, 26.8],                    {                        name: Chrome,                        y: 12.8,                        sliced: true,                        selected: true                    },                    [Safari, 8.5],                    [Opera, 6.2],                    [Others, 0.7]                ]                    }]                });            });        });    </script></head><body>    <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto">    </div>    <div style="text-align:center; width:100%;">        <input type="button" value=http://www.mamicode.com/"保存图表至服务器(默认保存为PNG格式可自行调整)" onclick="SaveChart()" />    </div>    <script type="text/javascript" language="javascript">        //也可以直接用异步提交方式,这样可以防止页面刷新        function ExportChart() {            $.ajax(            {                type: POST, //post方式异步提交                async: false, //同步提交                url: "/highcharts_export.aspx", //导出图表的服务页面地址                dataType: "json", //传递方式为json                //几个重要的参数 如果这里不传递width的话,需要修改导出服务页面内的Request.Form["width"].ToString() 把这句代码注释掉即可                data: { type: image/png, filename: MyChartTest, width: 400, svg: chart.getSVG() },                success: function (msg) {                    alert("图表导出成功!");                },                error: function (errorMsg) {                    if (errorMsg.statusText == "OK") {                        alert("图表导出成功!");                    } else {                        alert("图表导出失败!");                    }                }            }            );        }        //保存图表        function SaveChart() {            chart.exportChart({                type: image/png,                filename: mychart            });        }    </script></body></html>

4.服务器上的代码:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO;using System.Text;using System.Drawing.Imaging;using iTextSharp.text.pdf;using iTextSharp.text;using Svg;using System.Xml;namespace HighCharts_Web{    public partial class HCExport : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            if (!Page.IsPostBack)            {                //判断参数是否正确                //type是可以自己指定的导出类型                //svg是默认传递的                //filename是可以自己指定的文件名                if (Request.Form["type"] != null && Request.Form["svg"] != null && Request.Form["filename"] != null)                {                    //获得相应参数                    string tType = Request.Form["type"].ToString();                    string tSvg = Request.Form["svg"].ToString();                    string tFileName = Request.Form["filename"].ToString();                    if (tFileName == "")                    {                        tFileName = "chart";                    }                    //将svg转换为二进制流                    MemoryStream tData = http://www.mamicode.com/new MemoryStream(Encoding.ASCII.GetBytes(tSvg));"";                    string tTypeString = "";                    //获取导出类型                    switch (tType)                    {                        case "image/png":                            tTypeString = "-m image/png";                            tExt = "png";                            break;                        case "image/jpeg":                            tTypeString = "-m image/jpeg";                            tExt = "jpg";                            break;                        case "application/pdf":                            tTypeString = "-m application/pdf";                            tExt = "pdf";                            break;                        case "image/svg+xml":                            tTypeString = "-m image/svg+xml";                            tExt = "svg";                            break;                    }                    if (tTypeString != "")                    {                        string tWidth = Request.Form["width"].ToString();                        SvgDocument tSvgObj = SvgDocument.Open<SvgDocument>(tData);                        switch (tExt)                        {                            case "jpg":                                tSvgObj.Draw().Save(tStream, ImageFormat.Jpeg);                                //DELETING SVG FILE                                 //if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile))                                //{                                //    File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);                                //}                                break;                            case "png":                                tSvgObj.Draw().Save(tStream, ImageFormat.Png);                                ////DELETING SVG FILE                                //if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile))                                //{                                //    File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);                                //}                                break;                            case "pdf":                                PdfWriter tWriter = null;                                Document tDocumentPdf = null;                                try                                {                                    // First step saving png that would be used in pdf                                    tSvgObj.Draw().Save(tStream, ImageFormat.Png);                                    // Creating pdf document                                    tDocumentPdf = new Document(new iTextSharp.text.Rectangle((float)tSvgObj.Width, (float)tSvgObj.Height));                                    // setting up margin to full screen image                                    tDocumentPdf.SetMargins(0.0f, 0.0f, 0.0f, 0.0f);                                    // creating image                                    iTextSharp.text.Image tGraph = iTextSharp.text.Image.GetInstance(tStream.ToArray());                                    tGraph.ScaleToFit((float)tSvgObj.Width, (float)tSvgObj.Height);                                    tStream = new MemoryStream();                                    // Insert content                                    tWriter = PdfWriter.GetInstance(tDocumentPdf, tStream);                                    tDocumentPdf.Open();                                    tDocumentPdf.NewPage();                                    tDocumentPdf.Add(tGraph);                                    tDocumentPdf.CloseDocument();                                    //// deleting png                                    //if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile.Substring(0, tOutputFile.LastIndexOf(".")) + ".png"))                                    //{                                    //    File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile.Substring(0, tOutputFile.LastIndexOf(".")) + ".png");                                    //}                                    //// deleting svg                                    //if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile))                                    //{                                    //    File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);                                    //}                                }                                catch (Exception ex)                                {                                    throw ex;                                }                                finally                                {                                    //正确释放资源                                    tDocumentPdf.Close();                                    tDocumentPdf.Dispose();                                    tWriter.Close();                                    tWriter.Dispose();                                    tData.Dispose();                                    tData.Close();                                }                                break;                            case "svg":                                tStream = tData;                                break;                        }                        //if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile))                        //{                        //Putting session to be able to delete file in temp directory                        //Session["sFileToTransmit_highcharts_export"] = File.ReadAllBytes(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile);                        //First step deleting disk file;                        //File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile);                        //保存图表路径 可以自己指定                        tFileName = Server.MapPath("~/Report/") + tFileName + "." + tExt;                        Response.ClearContent();                        Response.ClearHeaders();                        Response.ContentType = tType;                        //Response.AppendHeader("Content-Disposition", "attachment; filename=" + tFileName + "." + tExt + "");                        //将二进制流保存为指定路径下的具体文件                            System.IO.File.WriteAllBytes(tFileName, tStream.ToArray());                        //Response.BinaryWrite(tStream.ToArray());                                                    Response.Write("恭喜您,highcharts导出成功,路径为" + tFileName);                        Response.End();                        //}                    }                }            }        }    }}

 5,这样就可以将图表下载到服务器的Report文件夹中了,ok,不谢!

6。着力推荐关于本文中所解决的问题,让更多的爱好者都能学习到如此经典的方式。本文也是借鉴的。

http://www.stepday.com/topic/?594      http://www.stepday.com/topic/?725

在asp.net中如何自己编写highcharts图表导出到自己的服务器上来