highcharts 的Net导出服务  GitHub上整理的https://github.com/imclem/Highcharts-export-module-asp.net

引用两个程序集 sharpPDF.dll,Svg.dll (实际上就是将svg转化成其他格式的图片)

两种导出情况:  

1、只需要图片,修改自带导出按钮的请求路径路径就行
2、需要插入到word等二次处理再导出时

页面:

@{
ViewBag.Title = "Index";
} @section css{ } @section scripts{ <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="/Scripts/Highcharts-4.0.4/js/highcharts.js"></script>
<script src="/Scripts/Highcharts-4.0.4/js/highcharts-more.js"></script>
<script src="/Scripts/Highcharts-4.0.4/js/modules/exporting.js"></script> <script type="text/javascript">
var chart;
$(function () { var datas = {
chart: {
zoomType: 'xy'
},
title: {
text: 'Temperature vs Rainfall'
},
xAxis: [{
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
}],
yAxis: [{ // Primary yAxis
labels: {
format: '{value} °C',
style: {
color: Highcharts.getOptions().colors[]
}
},
title: {
text: 'Temperature',
style: {
color: Highcharts.getOptions().colors[]
}
}
}, { // Secondary yAxis
title: {
text: 'Rainfall',
style: {
color: Highcharts.getOptions().colors[]
}
},
labels: {
format: '{value} mm',
style: {
color: Highcharts.getOptions().colors[]
}
},
opposite: true
}], tooltip: {
shared: true
}, exporting: {
url: '/HighCharts/Export', //1、自带导出按钮的请求路径
filename: 'MyChart',
width:
},
series: [
{
name: 'Temperature',
type: 'spline',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6],
tooltip: {
pointFormat: '<span style="font-weight: bold; color: {series.color}">{series.name}</span>: <b>{point.y:.1f}°C</b> '
}
}, {
name: 'Temperature error',
type: 'errorbar',
data: [[, ], [5.9, 7.6], [9.4, 10.4], [14.1, 15.9], [18.0, 20.1], [21.0, 24.0], [23.2, 25.3], [26.1, 27.8], [23.2, 23.9], [18.0, 21.1], [12.9, 14.0], [7.6, 10.0]],
tooltip: {
pointFormat: '(error range: {point.low}-{point.high}°C)<br/>'
}
} , {
name: 't2===========',
type: 'spline',
data: [118.3, 13.9, 7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 9.6],
tooltip: {
pointFormat: '<span style="font-weight: bold; color: {series.color}">{series.name}</span>: <b>{point.y:.1f}°C</b> '
}
}, {
name: 't2============ error',
type: 'errorbar',
data: [[118.0, 121.1], [12.9, 14.0], [, ], [5.9, 7.6], [9.4, 10.4], [14.1, 15.9], [18.0, 20.1], [21.0, 24.0], [23.2, 25.3], [26.1, 27.8], [23.2, 23.9], [7.6, 10.0]],
tooltip: {
pointFormat: '(error range: {point.low}-{point.high}°C)<br/>'
}
} ]
};
$('#container-Test').highcharts(datas);
$('#container-Test2').highcharts(datas);
}); // 2、插入到word等二次处理导出时用到
//点击一个按钮导出图片
function exportClick() { var chartTest = $('#container-Test').highcharts();
var svgData = chartTest.getSVG(); $.post('/HighCharts/ManualExport', { filename: "手动导出的图片", type: "image/png", width: , svg: svgData }, function (r) {
if (!r.state) return; window.location.href = r.downloadpath;
},'json'); } </script> } <h2>Index</h2> <div> <input type="button" value="点击一个按钮导出图片" onclick="exportClick()"/>
</div> <div id="container-Test" style="height: 400px; margin: auto; min-width: 310px; max-width: 600px"></div>
<hr />
<div id="container-Test2" style="height: 400px; margin: auto; min-width: 310px; max-width: 600px"></div>

xxoo Code

控制器: 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Timers;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using xxoo.Common.HighChart; namespace ToolsSite.Controllers
{
public class HighChartsController : Controller
{
//
// GET: /HighCharts/ public ActionResult Index()
{ return View();
} #region1、 自带的导出按钮
//修改 HighChart 导出服务器路径
//exporting: { url: '/HighCharts/Export', filename: 'MyChart', width: 1200 },
[ValidateInput(false)]
[HttpPost]
public ActionResult Export(string filename, string type, int width,string svg)
{ Exporter export = new Exporter(filename, type, width, svg); //// 1、文件名输出
//FileStream fileWrite = new FileStream(@"d:\HighCharts导出图片.png", FileMode.Create, FileAccess.Write);
//ExportFileInfo fi = export.WriteToStream(fileWrite);
//string fileName = "导出的图片." + fi.Extension;
//fileWrite.Close();
//fileWrite.Dispose();
//return File(@"d:\HighCharts导出图片.png", fi.ContentType, fileName); // 2、 字节输出
ExportFileInfo fi;
byte[] buffer = export.WriteToBuffer(out fi);
string fileName = "导出的图片." + fi.Extension;
return File(buffer, fi.ContentType, fileName);
}
#endregion #region 2、 点击一个按钮导出图片 (插入到word等二次处理导出时用到) [ValidateInput(false)]
[HttpPost]
public ActionResult ManualExport(string filename, string type, int width, string svg)
{
Exporter export = new Exporter(filename, type, width, svg);
string fileId = Guid.NewGuid().ToString();
string tempFilePath = Request.MapPath("~/DownFile/") + fileId; // 1、文件名输出
FileStream fileWrite = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write);
ExportFileInfo fi = export.WriteToStream(fileWrite);
filename += "." + fi.Extension;
fileWrite.Close();
fileWrite.Dispose(); Timer tr = new Timer( * * ); // 1分钟后删除
tr.Elapsed += (s, e) =>
{
if (System.IO.File.Exists(tempFilePath))
{
System.IO.File.Delete(tempFilePath);
}
};
tr.Start(); string downloadPath = string.Format( "/HighCharts/ManualDownload?fileId={0}&ContentType={1}&fileName={2}"
, fileId,fi.ContentType, filename); var o = new { state = true, downloadpath = downloadPath };
string result = JsonConvert.SerializeObject(o); return Content(result);
} // 手动下载导出文件
[HttpGet]
public ActionResult ManualDownload(string fileId, string ContentType,string fileName)
{
string tempFilePath = Request.MapPath("~/DownFile/") + fileId;
if (!System.IO.File.Exists(tempFilePath))
{
return Redirect("/HighCharts/Index?msg=文件已失效");
} byte[] buffer = System.IO.File.ReadAllBytes(tempFilePath);
System.IO.File.Delete(tempFilePath);
return File(buffer, ContentType, fileName);
} #endregion }
}

xxoo Code

工具类:  

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using sharpPDF;
using Svg;
using Svg.Transforms; namespace xxoo.Common.HighChart
{
/// <summary>
/// Processes web requests to export Highcharts JS JavaScript charts.
/// </summary>
internal static class ExportChart
{
/// <summary>
/// Processes HTTP Web requests to export SVG.
/// </summary>
/// <param name="context">An HttpContext object that provides references
/// to the intrinsic server objects (for example, Request, Response,
/// Session, and Server) used to service HTTP requests.</param>
internal static void ProcessExportRequest(HttpContext context)
{
if (context != null &&
context.Request != null &&
context.Response != null &&
context.Request.HttpMethod == "POST")
{
HttpRequest request = context.Request; // Get HTTP POST form variables, ensuring they are not null.
string filename = request.Form["filename"];
string type = request.Form["type"];
int width = ;
string svg = request.Form["svg"]; if (filename != null &&
type != null &&
Int32.TryParse(request.Form["width"], out width) &&
svg != null)
{
// Create a new chart export object using form variables.
Exporter export = new Exporter(filename, type, width, svg); // Write the exported chart to the HTTP Response object.
export.WriteToHttpResponse(context.Response); // Short-circuit this ASP.NET request and end. Short-circuiting
// prevents other modules from adding/interfering with the output.
HttpContext.Current.ApplicationInstance.CompleteRequest();
context.Response.End();
}
}
} internal static void ProcessExportRequest(string filename, string type, string svg,string widthStr,Stream stream)
{
// Get HTTP POST form variables, ensuring they are not null.
int width = ; if (filename != null &&
type != null &&
Int32.TryParse(widthStr, out width) &&
svg != null)
{
// Create a new chart export object using form variables.
Exporter export = new Exporter(filename, type, width, svg); // Write the exported chart to the HTTP Response object.
export.WriteToStream(stream); // Short-circuit this ASP.NET request and end. Short-circuiting
// prevents other modules from adding/interfering with the output.
HttpContext.Current.ApplicationInstance.CompleteRequest();
HttpContext.Current.Response.End();
}
}
} /// <summary>
/// 导出的文件信息
/// </summary>
internal class ExportFileInfo
{
/// <summary>
/// 文件扩展名
/// </summary>
public string Extension { get; set; }
/// <summary>
/// 响应输出文件类型
/// </summary>
public string ContentType { get; set; }
} /// <summary>
/// .NET chart exporting class for Highcharts JS JavaScript charts.
/// </summary>
internal class Exporter
{
/// <summary>
/// Default file name to use for chart exports if not otherwise specified.
/// </summary>
private const string DefaultFileName = "Chart"; /// <summary>
/// PDF metadata Creator string.
/// </summary>
private const string PdfMetaCreator =
"Tek4(TM) Exporting Module for Highcharts JS from Tek4.com"; /// <summary>
/// Gets the HTTP Content-Disposition header to be sent with an HTTP
/// response that will cause the client's browser to open a file save
/// dialog with the proper file name.
/// </summary>
public string ContentDisposition { get; private set; } /// <summary>
/// Gets the MIME type of the exported output.
/// </summary>
public string ContentType { get; private set; } /// <summary>
/// Gets the file name with extension to use for the exported chart.
/// </summary>
public string FileName { get; private set; } /// <summary>
/// Gets the chart name (same as file name without extension).
/// </summary>
public string Name { get; private set; } /// <summary>
/// Gets the SVG chart document (XML text).
/// </summary>
public string Svg { get; private set; } /// <summary>
/// Gets the pixel width of the exported chart image.
/// </summary>
public int Width { get; private set; } /// <summary>
/// Initializes a new chart Export object using the specified file name,
/// output type, chart width and SVG text data.
/// </summary>
/// <param name="fileName">The file name (without extension) to be used
/// for the exported chart.</param>
/// <param name="type">The requested MIME type to be generated. Can be
/// 'image/jpeg', 'image/png', 'application/pdf' or 'image/svg+xml'.</param>
/// <param name="width">The pixel width of the exported chart image.</param>
/// <param name="svg">An SVG chart document to export (XML text).</param>
internal Exporter(
string fileName,
string type,
int width,
string svg)
{
string extension; this.ContentType = type.ToLower();
this.Name = fileName;
this.Svg = svg;
this.Width = width; // Validate requested MIME type.
switch (ContentType)
{
case "image/jpeg":
extension = "jpg";
break; case "image/png":
extension = "png";
break; case "application/pdf":
extension = "pdf";
break; case "image/svg+xml":
extension = "svg";
break; // Unknown type specified. Throw exception.
default:
throw new ArgumentException(
string.Format("Invalid type specified: '{0}'.", type));
} // Determine output file name.
this.FileName = string.Format(
"{0}.{1}",
string.IsNullOrEmpty(fileName) ? DefaultFileName : fileName,
extension); // Create HTTP Content-Disposition header.
this.ContentDisposition =
string.Format("attachment; filename={0}", this.FileName);
} /// <summary>
/// Creates an SvgDocument from the SVG text string.
/// </summary>
/// <returns>An SvgDocument object.</returns>
private SvgDocument CreateSvgDocument()
{
SvgDocument svgDoc; // Create a MemoryStream from SVG string.
using (MemoryStream streamSvg = new MemoryStream(
Encoding.UTF8.GetBytes(this.Svg)))
{
svgDoc = SvgDocument.Open<SvgDocument>(streamSvg);
} // Scale SVG document to requested width.
svgDoc.Transforms = new SvgTransformCollection();
float scalar = (float)this.Width / (float)svgDoc.Width;
svgDoc.Transforms.Add(new SvgScale(scalar, scalar));
svgDoc.Width = new SvgUnit(svgDoc.Width.Type, svgDoc.Width * scalar);
svgDoc.Height = new SvgUnit(svgDoc.Height.Type, svgDoc.Height * scalar); return svgDoc;
} /// <summary>
/// Exports the chart to the specified HttpResponse object. This method
/// is preferred over WriteToStream() because it handles clearing the
/// output stream and setting the HTTP reponse headers.
/// </summary>
/// <param name="httpResponse"></param>
internal void WriteToHttpResponse(HttpResponse httpResponse)
{
httpResponse.ClearContent();
httpResponse.ClearHeaders();
httpResponse.ContentType = this.ContentType;
httpResponse.AddHeader("Content-Disposition", this.ContentDisposition);
WriteToStream(httpResponse.OutputStream);
} /// <summary>
/// 导出
/// </summary>
/// <param name="outputStream">流</param>
/// <returns>文件扩展名 和 ContentType</returns>
internal ExportFileInfo WriteToStream(Stream outputStream)
{
ExportFileInfo fi = new ExportFileInfo(); string[] fileExtenContentType = new string[]; switch (this.ContentType)
{
case "image/jpeg":
CreateSvgDocument().Draw().Save(
outputStream,
ImageFormat.Jpeg);
fi.Extension = "jpg";
fi.ContentType = "image/jpeg";
break; case "image/png":
// PNG output requires a seekable stream.
using (MemoryStream seekableStream = new MemoryStream())
{
CreateSvgDocument().Draw().Save(
seekableStream,
ImageFormat.Png);
seekableStream.WriteTo(outputStream);
}
fi.Extension = "png";
fi.ContentType = "image/png";
break; case "application/pdf":
SvgDocument svgDoc = CreateSvgDocument();
Bitmap bmp = svgDoc.Draw(); pdfDocument doc = new pdfDocument(this.Name, null);
pdfPage page = doc.addPage(bmp.Height, bmp.Width);
page.addImage(bmp, , );
doc.createPDF(outputStream);
fi.Extension = "pdf";
fi.ContentType = "application/pdf";
break; case "image/svg+xml":
using (StreamWriter writer = new StreamWriter(outputStream))
{
writer.Write(this.Svg);
writer.Flush();
}
fi.Extension = "svg";
fi.ContentType = "image/svg";
break; default:
throw new InvalidOperationException(string.Format(
"ContentType '{0}' is invalid.", this.ContentType));
} return fi;
} /// <summary>
/// 导出
/// </summary>
/// <param name="ExportFileInfo">文件信息</param>
/// <returns>图片字节数组</returns>
internal byte[] WriteToBuffer(out ExportFileInfo fi)
{
fi = new ExportFileInfo();
byte[] buffer = null;
int length = -;
// File(buffer, fileExtenContentType[1], fileName); string[] fileExtenContentType = new string[]; switch (this.ContentType)
{
case "image/jpeg":
using (MemoryStream seekableStream = new MemoryStream())
{
Bitmap bmp = CreateSvgDocument().Draw();
bmp.Save(
seekableStream,
ImageFormat.Jpeg);
buffer = seekableStream.GetBuffer();
}
fi.Extension = "jpg";
fi.ContentType = "image/jpeg";
break; case "image/png": // PNG output requires a seekable stream.
using (MemoryStream seekableStream = new MemoryStream())
{
CreateSvgDocument().Draw().Save(
seekableStream,
ImageFormat.Png);
buffer = seekableStream.GetBuffer();
}
fi.Extension = "png";
fi.ContentType = "image/png";
break; case "application/pdf":
using (MemoryStream seekableStream = new MemoryStream())
{
SvgDocument svgDoc = CreateSvgDocument();
Bitmap bmp = svgDoc.Draw(); pdfDocument doc = new pdfDocument(this.Name, null);
pdfPage page = doc.addPage(bmp.Height, bmp.Width);
page.addImage(bmp, , );
doc.createPDF(seekableStream);
buffer = seekableStream.GetBuffer();
}
fi.Extension = "pdf";
fi.ContentType = "application/pdf";
break; case "image/svg+xml": buffer = Encoding.UTF8.GetBytes(this.Svg);
fi.Extension = "svg";
fi.ContentType = "image/svg";
break; default:
throw new InvalidOperationException(string.Format(
"ContentType '{0}' is invalid.", this.ContentType));
} return buffer;
} } /* 调用示例
* 引用程序集: sharpPDF.dll,Svg.dll
*
//修改 HighChart 导出服务器路径
//exporting: { url: '/HighCharts/Export', filename: 'MyChart', width: 1200 },
[ValidateInput(false)]
[HttpPost]
public ActionResult Export(string filename, string type, int width,string svg)
{ Exporter export = new Exporter(filename, type, width, svg); //// 1、文件名输出
//FileStream fileWrite = new FileStream(@"d:\HighCharts导出图片.png", FileMode.Create, FileAccess.Write);
//ExportFileInfo fi = export.WriteToStream(fileWrite);
//string fileName = "导出的图片." + fi.Extension;
//fileWrite.Close();
//fileWrite.Dispose();
//return File(@"d:\HighCharts导出图片.png", fi.ContentType, fileName); // 2、 字节输出
ExportFileInfo fi;
byte[] buffer = export.WriteToBuffer(out fi);
string fileName = "导出的图片." + fi.Extension;
return File(buffer, fi.ContentType, fileName);
}
*/ }

xxoo Code

工具类和sharpPDF.dll,Svg.dll程序集下载  
http://download.csdn.net/detail/qq_21533697/9467247

highcharts .net导出服务 和 两种导出方式的更多相关文章

  1. Android四大组件之服务的两种启动方式详解

    Service简单概述 Service(服务):是一个没有用户界面.可以在后台长期运行且可以执行操作的应用组件.服务可由其他应用组件启动(如:Activity.另一个service).此外,组件可以绑 ...

  2. 三,memcached服务的两种访问方式

    memcached有两种访问方式,分别是使用telnet访问和使用php访问. 1,使用telnet访问memcacehd 在命令提示行输入, (1)连接memcached指令:telnet 127. ...

  3. (转)DLL中导出函数的两种方式(dllexport与.def文件)

    DLL中导出函数的两种方式(dllexport与.def文件)http://www.cnblogs.com/enterBeijingThreetimes/archive/2010/08/04/1792 ...

  4. 【转】DLL中导出函数的两种方式(dllexport与.def文件)

    DLL中导出函数的两种方式(dllexport与.def文件) DLL中导出函数的声明有两种方式: 一种方式是:在函数声明中加上__declspec(dllexport):另外一种方式是:采用模块定义 ...

  5. vue项目中导出PDF的两种方式

    参考大家导出的方式,基本上是如下两种: 1.使用 html2Canvas + jsPDF 导出PDF, 这种方式什么都好,就是下载的pdf太模糊了.对要求好的pdf这种方式真是不行啊! 2.调用浏览器 ...

  6. .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)

    .Net MVC  导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构)   public cl ...

  7. Linux 服务管理两种方式service和systemctl

    Linux 服务管理两种方式service和systemctl 1.service命令 service命令其实是去/etc/init.d目录下,去执行相关程序 # service命令启动redis脚本 ...

  8. linux安装mysql服务分两种安装方法:

    linux安装mysql服务分两种安装方法: ①源码安装,优点是安装包比较小,只有十多M,缺点是安装依赖的库多,安装编译时间长,安装步骤复杂容易出错: ②使用官方编译好的二进制文件安装,优点是安装速度 ...

  9. 探究Redis两种持久化方式下的数据恢复

    对长期奋战在一线的后端开发人员来说,都知道redis有两种持久化方式RDB和AOF,虽说大家都知道这两种方式大概运作方式,但想必有实操的人不会太多. 这里是自己实操两种持久化方式的一点点记录. 先看以 ...

随机推荐

  1. 一次页面从Jq到Vuejs+PartialView的迁徙

    题外话 本篇分享不能帮助你入门vue,入门的文章也是无意义的,官方文档http://cn.vuejs.org/v2/guide/ 已经写的不能再清晰了.希望我们勇敢的主动地给自己创造实践的机会. 手里 ...

  2. .net 预防用户复制页面地址直接进入

    用户将某一页面的地址直接复制到另一个浏览器窗口(或者将链接地址分享给其他人),假如页面需要参数的时候因为直接进入没有从其他页面跳转,参数不存在,可能得不到想要的结果 处理方法:让页面跳到首页重新进入: ...

  3. C#开发微信门户及应用(2)--微信消息的处理和应答

    微信应用如火如荼,很多公司都希望搭上信息快车,这个是一个商机,也是一个技术的方向,因此,有空研究下.学习下微信的相关开发,也就成为计划的安排事情之一了.本系列文章希望从一个循序渐进的角度上,全面介绍微 ...

  4. BZOJ3095 : 二元组

    \[\begin{eqnarray*}&&\sum_{i=0}^{n-1}\left(ki+b-a_i\right)^2\\&=&\sum_{i=0}^{n-1}\le ...

  5. spring源码:web容器启动(li)

    web项目中可以集成spring的ApplicationContext进行bean的管理,这样使用起来bean更加便捷,能够利用到很多spring的特性.我们比较常用的web容器有jetty,tomc ...

  6. 使用Mavne生成可以执行的jar文件

    到目前为之,还没有运行HelloWorld的项目,不要忘了HelloWorld类可是有一个main方法的.使用mvn clean install命令默认生成的jar 包是不能直接运行的.因为带有mai ...

  7. Java web.xml 配置详解

    在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是 ...

  8. SVG坐标系统

    SVG的画布.画布视区(viewBox).浏览器视窗的概念 画布 画布是绘制SVG内容的一块区域,理论上在所有维度上都是无限的.(也有人称为"SVG世界",但我觉得叫画布比较合适) ...

  9. Android开发aidl使用中linkToDeath和unlinkToDeath的使用

    1.Binder死亡代理     这一节首先将介绍Binder类中比较重要的两个方法linkToDeath和unlinkToDeath.我们知道Binder是运行在服务进程,若服务端进程因为某种原因“ ...

  10. 手机游戏渠道SDK接入工具项目分享(一)缘起

    #剧情章节 # 上周刚结束一个外包的项目,开发手机游戏渠道SDK聚合接入工具的,现在有空回顾整理一下这个项目开发过程,因涉嫌商业秘密不会提供项目代码,只谈下开发思路和掉过的坑. 本人多年从事手机互联网 ...