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)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
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({})中加入下面代码
1
2
3
4
|
exporting:{
filename:
'class-booking-chart'
,
url:
'http://export.highcharts.com/'
}
|