Specify the exporting URL on client side:
Code: Select all
new Highcharts.Chart({
exporting: {
url: 'chart-export',
...
},
Code: Select all
import org.apache.batik.transcoder.*;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.fop.svg.PDFTranscoder;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
@Path("chart-export")
public class ChartExportResource {
public ChartExportResource() {
}
@POST
public Response doExport(@FormParam("filename") @DefaultValue("chart") String fileName,
@FormParam("width") @DefaultValue("800") float width,
@FormParam("type") @DefaultValue("application/pdf") String type,
@FormParam("svg") String svg) throws TranscoderException
{
String suffix = "";
byte[] data;
String charset = "";
if ("image/svg+xml".equals(type)) {
suffix = ".svg";
data = getUtf8Bytes(svg);
charset = ";charset=utf-8";
}
else {
Transcoder transcoder;
if ("application/pdf".equals(type)) {
transcoder = new PDFTranscoder();
suffix = ".pdf";
}
else if ("image/png".equals(type)) {
transcoder = new PNGTranscoder();
suffix = ".png";
}
else if ("image/jpeg".equals(type)) {
transcoder = new JPEGTranscoder();
suffix = ".jpeg";
}
else {
throw new IllegalArgumentException("Cannot export chart. Unsupported type " + type);
}
data = transcode(transcoder, width, svg);
}
//noinspection StringToUpperCaseOrToLowerCaseWithoutLocale
if (!fileName.toLowerCase().endsWith(suffix)) {
fileName += suffix;
}
Response.ResponseBuilder responseBuilder = Response.ok(data, type + charset)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
return responseBuilder.build();
}
private byte[] transcode(Transcoder transcoder, float width, String svg) throws TranscoderException {
transcoder.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, width);
TranscoderInput input = new TranscoderInput(new StringReader(svg));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TranscoderOutput output = new TranscoderOutput(baos);
transcoder.transcode(input, output);
byte[] data = baos.toByteArray();
return data;
}
private byte[] getUtf8Bytes(String text) {
try {
return text.getBytes("utf-8");
}
catch (UnsupportedEncodingException ignore) {
// Can't happen: UTF-8 is guaranteed to be supported by Java
return null;
}
}
}