Highcharts是一個用純JavaScript編寫的圖表庫,提供了一個交互式的圖表添加到您的網站或Web應用程序的簡單方法。Highcharts目前支持線,樣條,面積,areaspline,柱形圖,條形圖,餅圖和散點圖類型。
同時Highcharts提供將圖表導出為圖片或者PDF格式文件,只需要在頁面中載入exporting.js文件。
由于生成的圖表是SVG格式,所以導出時需要將數據發送到服務器端來進行轉換。在exporting.js中默認導出地址是http://export.highcharts.com/,另外在demo中也提供了php版本。
本文是介紹如何在java web application中來實現導出功能。
首選需要在lib中加入batik jar包,如果是使用maven來管理項目,則在庫中只能找到1.6的版本,同時需要另外下載一個包(xml-apis-ext.jar)。
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。
batik 1.6版本中好像沒有提供對pdf格式導出的支持,所有如果程序報錯,就把導出為pdf的功能去掉。
filename和export url都有默認值,可以在生成chart的配置中指定filename和我們自己的export url。在new Highcharts.Chart({})中加入下面代碼
exporting:{
filename:'class-booking-chart',
url:'http://export.highcharts.com/'
}
其他基本就可以直接將demo的數據修改為自己需要的。
本文來自http://www.hencuo.com/archives/109
//可以設置下編碼,解決中文亂碼問題
response.setContentType(“text/html; charset=” + encoding);
//并用OutputStreamWriter包裝ServletOutputStream轉換iso-8859-1為UTF-8可輸出中文內容
OutputStreamWriter writer = new OutputStreamWriter(out, “UTF-8″);
else if (ext.equals(“svg”)) {
// image/svg+xml
writer.append(svg);
writer.flush();
}