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的數據修改成本身須要的。