In this example will create a exporting server for Highchart in Java. Since the default example is in PHP, and I'm using Java and tomcat as my web server.
I convert the PHP exporting script example to Java servlet code.
public class ReportExporter extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
ServletContext application = this.getServletContext();
String type = request.getParameter("type");
String svg = request.getParameter("svg");
String filename = request.getParameter("filename");
System.out.println("type: " + type);
System.out.println("svg: " + svg);
System.out.println("filename: " + filename);
System.out.println("width: " + request.getParameter("width"));
if (filename == null && filename.equals("")) {
filename = "chart";
}
String typeString = "";
String ext = "";
String outFile = "";
String width = null;
String tempName = null;
try {
tempName = SecurityUtil.md5(String.valueOf(System
.currentTimeMillis()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (type.equals("image/png")) {
typeString = "-m image/png";
ext = "png";
} else if (type.equals("image/jpeg")) {
typeString = "-m image/jpeg";
ext = "jpg";
} else if (type.equals("application/pdf")) {
typeString = "-m application/pdf";
ext = "pdf";
} else if (type.equals("image/svg+xml")) {
ext = "svg";
}
outFile = "temp/" + tempName + "." + ext;
if (!typeString.equals("")) {
width = request.getParameter("width");
if (width != null && !width.equals(""))
width = "-w " + width;
}
// Generate temporary file
File f = new File(application.getRealPath("/temp/" + tempName
+ ".svg"));
IOUtil.writeToFile(f, svg);
String batikPath = application.getRealPath("/WEB-INF/lib/batik-rasterizer.jar");
String classPath = "-cp " + application.getRealPath("/WEB-INF/lib");
String outFileFullPath = application.getRealPath(outFile);
String tempFileFullPath = application.getRealPath("temp/"+tempName+".svg");
try {
// Convert SVG file into specified type
SystemUtil.runCommand("java",classPath, "-jar",batikPath, typeString,"-d",outFileFullPath,width,tempFileFullPath);
// Show the file to user as download
response.setHeader("Content-disposition", "attachment; filename=" + filename + "." +ext);
response.setHeader("Content-type", type);
ServletOutputStream out = response.getOutputStream();
IOUtil.fileToStream(new File(outFileFullPath), out);
out.flush();
out.close();
} catch (Throwable e) {
e.printStackTrace();
response.getOutputStream().print("Error on exporting");
}
}
}
You will need these classes
SystemUtil
IOUtil
This example use Batik rasterizer. Please
download it here. Then place it your web application folder
WEB-INF/lib/batik-rasterizer.jar
WEB-INF/lib/batik-slideshow.jar
WEB-INF/lib/batik-squiggle.jar
WEB-INF/lib/batik-svgpp.jar
WEB-INF/lib/batik-ttf2svg.jar
WEB-INF/lib/lib -> contains lib for batik (see batik distribution batik-version/lib)