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();
}
}