Highcharts exports images,

Source: Internet
Author: User

Highcharts exports images,

Overview:

Highcharts is the first choice for everyone when a project involves a statistical chart. It also uses the export function of highcharts to export the Statistical Chart as an image. This is exactly the case, summary for future use.


Export method:

There are three ways to export highcharts images: highcharts server export, LAN server export, and local background export.

First, the highcharts server exports data using the default export method. You only need to configure the export parameter in the chart, but this export method needs to be networked;

Second, if you want to export LAN servers, you need to configure the exported servers in the LAN. For details, refer to http://www.highcharts.com/docs/export-module/setting-up-the-server;

Finally, exporting data in the local backend requires no Internet connection or LAN servers. You can directly write the corresponding servlet in the background, which is the focus of this article.


Export principle:

Highcharts chart export (or download) is essentially a process of converting SVG code into different file formats. The tool used is batik. Therefore, the so-called export server only calls batik, convert and download the SVG code. See:


The code for generating images using SVG in Java is as follows:

package com.lzugis.demo;import java.io.FileOutputStream;import java.io.OutputStream;import java.io.StringReader;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;public class CreateImg {public static void main(String[] args) throws Exception {String svg = "<svg height=\"200\" xmlns=\"http://www.w3.org/2000/svg\"><polygon points=\"10,10 75,150 150,60\" style=\"fill:#63BCF7;stroke:black;stroke-width:3\"/></svg>";String type="image/png";String filename="svg";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();    }    if (null != t) {    OutputStream out = new FileOutputStream("D:\\"+filename+"."+ext);    TranscoderInput input = new TranscoderInput(new StringReader(svg));TranscoderOutput output = new TranscoderOutput(out);try{    t.transcode(input, output);    System.out.println("out");} catch (TranscoderException e) {    e.printStackTrace();}    }}}}
After the image is generated, the effect is as follows:



In the web, the servlet code is as follows:

Package com. lzugis. 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. using Transcoder; import org. apache. batik. transcoder. image. PNGTranscoder; public class SaveAsImage extends HttpServlet {private static final long serialVersionUID = 1L; 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 {request. setCharacterEncoding ("UTF-8"); // sets the encoding to solve the garbled String type = req Uest. getParameter ("type"); String svg = request. getParameter ("svg"); String filename = request. getParameter ("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 encrypted Transcoder ();} else if (type. equals ("image/svg + xml") ext = "svg"; response. addHeader ("Content-Disposition", "attachment; filename =" + filename + ". "+ ext); response. addHeader ("Content-T Ype ", type); if (null! = T) {TranscoderInput input = new TranscoderInput (new StringReader (svg); TranscoderOutput = 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") {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 }}
The servlet configuration in web. xml is as follows:

  <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>
On the frontend, the call method is as follows:

Var chart; $ (document ). ready (function () {Highcharts. setOptions ({lang: {printChart: "Print Chart", downloadJPEG: "Download JPEG image", downloadPDF: "Download PDF Document", downloadPNG: "Download PNG Image", downloadSVG: "Download SVG vector graph", exportButtonTitle: "export image"}); chart = new Highcharts. chart ({chart: {renderTo: 'Container', defaultSeriesType: 'line', marginRight: 130, marginBottom: 25}, title: {text: 'monthly Average Temperature ', x: -20 // center}, subtitle: {text: 'test Chinese garbled ', 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: {enabled: true, filename: 'class-booking-chart', url: 'http: // localhost: 8081/HighChartsDemo/SaveAsImage '}, tooltip: {formatter: function () {return' <B> '+ this. series. name + '</B> <br/>' + this. x + ':' + this. y + Â ° C' ;}}, legend: {layout: 'vertical ', align: 'right', verticalign: 'middle', borderWidth: 0}, series: [{name: 'Tokyo ', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5]}, {name: 'New York ', data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1]}, {name: 'berline', data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3]}, {name: 'London ', data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3]});

Similarly, if you do not want to display the export button on the image, you can use chart. the getSVG () function obtains the svg element of the chart and sends it to the background in ajax mode. The Code is as follows:

            $("#export").click(function(){            var svg = chart.getSVG();            $.ajax({            type: "post",            url: 'http://localhost:8081/HighChartsDemo/SaveAsImage',            data:{            type:"image/png",            filename:"chart",            svg:svg            },            success: function(data){            console.log("success");            }            });            });

Batik lib package: http://pan.baidu.com/s/1dDwEvqL





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.