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. Nancy之实现API的功能

    0x01.前言 现阶段,用来实现API的可能大部分用的是ASP.NET Web API或者是ASP.NET MVC,毕竟是微软官方出产的,用的人也多. 但是呢,NancyFx也是一个很不错的选择.毕竟 ...

  2. .NET 实现并行的几种方式(四)

    本随笔续接:.NET 实现并行的几种方式(三) 八.await.async - 异步方法的秘密武器 1) 使用async修饰符 和 await运算符 轻易实现异步方法 前三篇随笔已经介绍了多种方式.利 ...

  3. C#开发微信门户及应用(26)-公众号微信素材管理

    微信公众号最新修改了素材的管理模式,提供了两类素材的管理:临时素材和永久素材的管理,原先的素材管理就是临时素材管理,永久素材可以永久保留在微信服务器上,微信素材可以在上传后,进行图片文件或者图文消息的 ...

  4. Yii 2.x Behavior - 类图

    yii\base\Component  继承这个类的类都具备扩展行为的能力

  5. CentOS 7 下安装redis步骤

    1. 从redis官网下载redis源码,本例安装在/usr/opt下 [root@localhost opt]# pwd /usr/opt [root@localhost opt]# wget ht ...

  6. IE 浏览器各个版本 JavaScript 支持情况一览表

    语言元素 语言元素 突发.IE6 标准.IE7 标准 IE8 标准 IE 9 标准 IE 10 标准 边缘 Windows 应用商店应用程序 __proto__ 属性 (Object) (JavaSc ...

  7. 使用MyBatis Generator自动创建代码(dao,mapping,poji)

    连接的数据库为SQL server2008,所以需要的文件为sqljdbc4.jar 使用的lib库有: 在lib库目录下新建一个src文件夹用来存放生成的文件,然后新建generatorConfig ...

  8. ListView和Adapter数据适配器的简单介绍

    ListView 显示大量相同格式数据 常用属性: listSelector            listView每项在选中.按下等不同状态时的Drawable divider            ...

  9. github源码学习之UIImage+YYWebImage

    UIImage+YYWebImage是YYWebImage(https://github.com/ibireme/YYWebImage)中的一个分类,这个分类封装了一些image常用的变化方法,非常值 ...

  10. CALayer的transform属性

    先来与View比较一下 View:transform -> CGAffineTransformRotate... layer:transform -> CATransform3DRotat ...