首页 > 代码库 > Java导出Highcharts生成的图表为图片源码

Java导出Highcharts生成的图表为图片源码

本文转载自:http://blog.csdn.net/dengsilinming/article/details/7352054

需要的jar包:

需要的js文件:(可以通过http://www.highcharts.com/download下载highcharts对应的js文件)

下面是一些主要部分

web.xml

<?xml version="1.0" encoding="UTF-8"?>  <web-app version="2.5"       xmlns="http://java.sun.com/xml/ns/javaee"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">    <servlet>      <description>This is the description of my J2EE component</description>      <display-name>This is the display name of my J2EE component</display-name>      <servlet-name>SaveAsImage</servlet-name>      <servlet-class>com.foxconn.highcharts.demo.SaveAsImage</servlet-class>    </servlet>      <servlet-mapping>      <servlet-name>SaveAsImage</servlet-name>      <url-pattern>/SaveAsImage</url-pattern>    </servlet-mapping>    <welcome-file-list>      <welcome-file>basic_line.jsp</welcome-file>    </welcome-file-list>  </web-app>

servlet部分

package com.foxconn.highcharts.demo;    import java.io.IOException;  import java.io.OutputStreamWriter;  import java.io.StringReader;    import javax.servlet.ServletException;  import javax.servlet.ServletOutputStream;  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;    import org.apache.batik.transcoder.Transcoder;  import org.apache.batik.transcoder.TranscoderException;  import org.apache.batik.transcoder.TranscoderInput;  import org.apache.batik.transcoder.TranscoderOutput;  import org.apache.batik.transcoder.image.JPEGTranscoder;  import org.apache.batik.transcoder.image.PNGTranscoder;  //import org.apache.fop.svg.PDFTranscoder;          public class SaveAsImage extends HttpServlet {        /**      *       */      private static final long serialVersionUID = 1L;        /**      * Constructor of the object.      */      public SaveAsImage() {          super();      }        /**      * Destruction of the servlet. <br>      */      public void destroy() {          super.destroy(); // Just puts "destroy" string in log      }        public void doGet(HttpServletRequest request, HttpServletResponse response)              throws ServletException, IOException {          doPost(request, response);      }            public void doPost(HttpServletRequest request, HttpServletResponse response)              throws ServletException, IOException {            /*导成pdf做了很久,但还是没能做出来,因为一直报         * java.lang.NoSuchMethodError: org.apache.avalon.framework.configuration.DefaultConfiguration.<init>(Ljava/lang/String;)V的错误,         * 如果你知道如何解决这个错误,请告诉我一下,在此先谢过了。现在已经可以正确地将图片导成pdf了,程序是没有问题的         * */          request.setCharacterEncoding("utf-8");//设置编码,解决乱码问题          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 =(Transcoder) new PDFTranscoder();//我将这儿的注释去掉了,因为导成pdf的问题已经解决              } else if(type.equals("image/svg+xml"))                   ext = "svg";                 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);                  OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");                  writer.append(svg);                  writer.close();              } 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();      }        /**      * Initialization of the servlet. <br>      *      * @throws ServletException if an error occurs      */      public void init() throws ServletException {          // Put your code here      }    } 

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"      pageEncoding="UTF-8"%>  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  <html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  <title>Basic Line</title>  <script src="js/jquery.min.js" type="text/javascript"></script>      <script src="js/excanvas.compiled.js" type="text/javascript"></script>      <script src="js/highcharts.js" type="text/javascript"></script>            <script src="js/highcharts.src.js" type="text/javascript"></script>      <script type="text/javascript" src="js/exporting.js"></script>      <script type="text/javascript">          var chart;          $(document).ready(function(){              chart = new Highcharts.Chart({                  chart: {                      renderTo: container,                      defaultSeriesType: line,                      marginRight: 130,                      marginBottom: 25              },              title: {                  text: Monthly Average Temperature,                  x: -20    //center              },              subtitle: {                  text: 测试中文乱码,                  x: -20              },              xAxis: {                  categories: [Jan, Feb, Mar, Apr, May, Jun,                                  Jul, Aug, Sep, Oct, Nov, Dec]              },              yAxis: {                  title: {                      text: Temperature (°C)                  },                  plotLines: [{                      value: 0,                      width: 1,                      color: #808080                  }]              },              exporting:{                  filename:chart,                  url:http://localhost:8080/HighChartsDemo/SaveAsImage//这里是一个重点哦,也可以修改exporting.js中对应的url              },              tooltip: {                  formatter: function(){                      return <b> + this.series.name + </b><br/> +                      this.x + :  + this.y + °C;                  }              },              legend: {                  layout: vertical,                  align: right,                  verticalAlign: middle,                  x: 10,                  y: 100,                  borderWidth: 0              },              series: [{                  name: Tokyo,                  data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]              },{                  name: New York,                  data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]              },{                  name: Berlin,                  data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]              },{                  name: London,                  data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]              }]              });          });      </script>  </head>  <body>      <div id="container" style="width: 100%; height: 400px"></div>  </body>  </html>  

项目源码可以通过点此下载 

注意:请下载源码的同学,将源码中的

/* else if (type.equals("application/pdf")) {                 ext = "pdf";                 t =(Transcoder) new PDFTranscoder();             }*/   

上面的注释去掉,程序是可以成功导出pdf的。