highcharts .net导出服务 和 两种导出方式
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导出服务 和 两种导出方式的更多相关文章
- Android四大组件之服务的两种启动方式详解
Service简单概述 Service(服务):是一个没有用户界面.可以在后台长期运行且可以执行操作的应用组件.服务可由其他应用组件启动(如:Activity.另一个service).此外,组件可以绑 ...
- 三,memcached服务的两种访问方式
memcached有两种访问方式,分别是使用telnet访问和使用php访问. 1,使用telnet访问memcacehd 在命令提示行输入, (1)连接memcached指令:telnet 127. ...
- (转)DLL中导出函数的两种方式(dllexport与.def文件)
DLL中导出函数的两种方式(dllexport与.def文件)http://www.cnblogs.com/enterBeijingThreetimes/archive/2010/08/04/1792 ...
- 【转】DLL中导出函数的两种方式(dllexport与.def文件)
DLL中导出函数的两种方式(dllexport与.def文件) DLL中导出函数的声明有两种方式: 一种方式是:在函数声明中加上__declspec(dllexport):另外一种方式是:采用模块定义 ...
- vue项目中导出PDF的两种方式
参考大家导出的方式,基本上是如下两种: 1.使用 html2Canvas + jsPDF 导出PDF, 这种方式什么都好,就是下载的pdf太模糊了.对要求好的pdf这种方式真是不行啊! 2.调用浏览器 ...
- .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)
.Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构) public cl ...
- Linux 服务管理两种方式service和systemctl
Linux 服务管理两种方式service和systemctl 1.service命令 service命令其实是去/etc/init.d目录下,去执行相关程序 # service命令启动redis脚本 ...
- linux安装mysql服务分两种安装方法:
linux安装mysql服务分两种安装方法: ①源码安装,优点是安装包比较小,只有十多M,缺点是安装依赖的库多,安装编译时间长,安装步骤复杂容易出错: ②使用官方编译好的二进制文件安装,优点是安装速度 ...
- 探究Redis两种持久化方式下的数据恢复
对长期奋战在一线的后端开发人员来说,都知道redis有两种持久化方式RDB和AOF,虽说大家都知道这两种方式大概运作方式,但想必有实操的人不会太多. 这里是自己实操两种持久化方式的一点点记录. 先看以 ...
随机推荐
- Redis简单案例(一) 网站搜索的热搜词
对于一个网站来说,无论是商城网站还是门户网站,搜索框都是有一个比较重要的地位,它的存在可以说是 为了让用户更快.更方便的去找到自己想要的东西.对于经常逛这个网站的用户,当然也会想知道在这里比较“火” ...
- 笔记:xubuntu下如何让系统默认使用nvidia显卡,而不是intel集显
经反复折腾,得到如下的解决方法: prime-select nvidia 简单吧,但关系是如果让它开机自动执行一次. 反复折腾了xinitrc ,~/.xinitrc , /etc/rc.local ...
- apache.commons.io.IOUtils: 一个很方便的IO工具库(比如InputStream转String)
转换InputStream到String, 比如 //引入apache的io包 import org.apache.commons.io.IOUtils; ... ...String str = IO ...
- spring源码:IOC(li)
一.BeanDefinition BeanDefinition是配置文件<bean>元素标签在容器中内部表示形式.创建最终的BeanDefinition主要包括两个步骤: 1)利用Bean ...
- jdk源码分析ArrayDeque
ArrayDeque 数组循环队列,这个数据结构设计的挺有意思的. 据说此类很可能在用作堆栈时快于 Stack,在用作队列时快于 LinkedList. 一.容量 1.1默认容量是8=2^3 1.2指 ...
- linux安装中文字体
一.查看系统字体 在开始安装之前,我们先查看系统中已经安装的字体. 要查看系统中已经安装的字体,我们可以使用fc-list命令进行查看.如果系统中没有该命令的话,我们需要先安装相关的软件包. 在cen ...
- eCharts 数据转换json
public ActionResult ShowChart() { return View(); } <div id="main" style="width:600 ...
- showSetPwdDialog--自定义对话框
样式: 布局: layout dialog_set_pwd.xml <?xml version="1.0" encoding="utf-8"?> & ...
- Android版本和API Level对应关系
http://developer.android.com/guide/topics/manifest/uses-sdk-element.html Platform Version API ...
- PHPmailer关于Extension missing: openssl报错的解决
最近在写一个网页的时候,需要用到PHPmailer来发送邮件,按照官网上给出的demo写出一个例子,却报错Extension missing: openssl 最后发现需要修改php.ini中的配置: ...