Highcharts是一个用纯JavaScript编写的图表库,提供了一个交互式的图表添加到您的网站或Web应用程序的简单方法。Highcharts目前支持线,样条,面积,areaspline,柱形图,条形图,饼图和散点图类型。php
同时Highcharts提供将图表导出为图片或者PDF格式文件,只须要在页面中载入exporting.js文件。html
因为生成的图表是SVG格式,因此导出时须要将数据发送到服务器端来进行转换。在exporting.js中默认导出地址是http://export.highcharts.com/,另外在demo中也提供了php版本。java
本文是介绍如何在java web application中来实现导出功能。web
首选须要在lib中加入batik jar包,若是是使用maven来管理项目,则在库中只能找到1.6的版本,同时须要另外下载一个包(xml-apis-ext.jar)。apache
public class ExportHighFreqChartServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { public ExportHighFreqChartServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServerException, IOException { String type = request.getParameter("type"); String svg = request.getParameter("svg"); String filename = request.getParameter("filename"); filename = filename==null?"chart":filename; ServletOutputStream out = response.getOutputStream(); if (null != type && null != svg) { svg = svg.replaceAll(":rect", "rect"); String ext = ""; Transcoder t = null; if (type.equals("image/png")) { ext = "png"; t = new PNGTranscoder(); } else if (type.equals("image/jpeg")) { ext = "jpg"; t = new JPEGTranscoder(); } else if (type.equals("application/pdf")) { ext = "pdf"; t = new PDFTranscoder(); } response.addHeader("Content-Disposition", "attachment; filename="+ filename + "."+ext); response.addHeader("Content-Type", type); if (null != t) { TranscoderInput input = new TranscoderInput(new StringReader(svg)); TranscoderOutput output = new TranscoderOutput(out); try { t.transcode(input, output); } catch (TranscoderException e) { out.print("Problem transcoding stream. See the web logs for more details."); e.printStackTrace(); } } else if (ext.equals("svg")) { out.print(svg); } else { out.print("Invalid type: " + type); } } else { response.addHeader("Content-Type", "text/html"); out.println("Usage:\n\tParameter [svg]: The DOM Element to be converted. \n\tParameter [type]: The destination MIME type for the elment to be transcoded."); } out.flush(); out.close(); } }
程序比较简单,接收页面传递的参数type、svg、filename,根据导出格式不一样new不一样的transcoder。api
batik 1.6版本中好像没有提供对pdf格式导出的支持,全部若是程序报错,就把导出为pdf的功能去掉。服务器
filename和export url都有默认值,能够在生成chart的配置中指定filename和咱们本身的export url。在new Highcharts.Chart({})中加入下面代码app
exporting:{ filename:'class-booking-chart', url:'http://export.highcharts.com/' }
其余基本就能够直接将demo的数据修改成本身须要的。