[Ext JS 4] exporting charts as png and jpg files

Source: Internet
Author: User

 

 

[Web Chart Series 6] canvas Chart export graph files

 

The principle of Chart export is very basic and has been introduced in the previous article.

For Extjs, in Ext. chart. the Chart class directly provides a save ([config]) method. By calling this method, you can download the graph file in the corresponding format of the current chart in browser.

 

chart.save({     type: 'image/png'});
The technology used here is to transmit data to the server, and then generate a map from the server to the front-end.

 

So when you call the save method, you will find that the request will access the http://svg.sencha.io/address.

Once, in the year of 2013, this address was accessible. At that time, the access to this address would report a 503 (Service Unavailable) error.

In this case, the chart export function that can work is not working now.

Search online to find that some versions do not provide this service.

In any case, if I talk about my services in other places, I am not always steadfast. Can I develop such services?

 

Principle

First, let's take a look at the parameters that are passed by the front-end during chart. save:

 

There are four parameters:

Width and height must be the image size.

Type should be the image storage format

Svg transmits svg data in xml format.

So the question is: how does the server parse the svg format data and generate image files?

 

Solution

Is it a solution to read the svg data and use basic APIs to generate an image?

But for java, is there any third-party package to help us directly do this?

One of the answers is:

BatikBatik is an application that uses svg format images to implement various functions and a java-based toolkit provided by Applet.

 

It is a project of the Apache Software Foundation and should be trustworthy.

Project home: http://xmlgraphics.apache.org/batik/

: Http://mirrors.cnnic.cn/apache/xmlgraphics/batik /,

Development steps:

1. Download batik-1.7.zip (the latest version) and decompress it.

2. Upload All lib packages under the root directory, lib and extensions to the web lib of the project. (Optional)

3. Write a servlet ImageExportService. java

 

/*** author:oscar999*/import java.io.IOException;import java.io.OutputStream;import java.io.StringReader;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;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 ImageExportService extends HttpServlet {/** *  */private static final long serialVersionUID = 1L;/** * Post File to Client * Input Parameters:  *  type(image type, as png, jpeg),  *  svg(svg string, post by extjs),  *  filename(save file name) */@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {String type = request.getParameter(type);String svg = request.getParameter(svg);String filename = chart;if( request.getParameter(filename)!=null&&request.getParameter(filename).length()>0){filename = request.getParameter(filename);}String postfix;if (image/jpeg.equals(type)) {response.setContentType(image/jpeg);postfix = jpg;} else {response.setContentType(image/png);postfix = png;}response.setHeader(Content-Disposition, attachment; filename= + filename + . + postfix);StringReader stringReader = new StringReader(svg);OutputStream out = response.getOutputStream();try {TranscoderInput input = new TranscoderInput(stringReader);TranscoderOutput output = new TranscoderOutput(out);if (image/jpeg.equals(type)) {new JPEGTranscoder().transcode(input, output);} else {new PNGTranscoder().transcode(input, output);}} catch (TranscoderException e) {throw new ServletException(e);}}}

4. Configure the servlet Request Path in web. xml

 

 

  
   
  
   ImageExportService
    
  
   com.XXX.ImageExportService
    
     
       
  
   ImageExportService
        
  
   /ImageExportService
    
 

 

5. Switch Chart. save of Extjs to the new server.

 

Ext.draw.engine.ImageExporter.defaultUrl = 'ImageExportService';
(Note: This part is written on the web end and can be placed in Ext. onReady)

 

 

6. Complete all. Write an example to test it.

 

//author: oscar999<script type=text/javascript>var chart;var panel1;Ext.require(['*']);Ext.onReady(function() {Ext.draw.engine.ImageExporter.defaultUrl = '/'+WEB_PROJECT_NAME+'/ImageExportService';var store = Ext.create('Ext.data.JsonStore', {    fields: ['name', 'data'],    data: [        { 'name': 'metric one',   'data':100000 },        { 'name': 'metric two',   'data': 7 },        { 'name': 'metric three', 'data': 5 },        { 'name': 'metric four',  'data': 2 },        { 'name': 'metric five',  'data':27 }    ]});var chart = Ext.create('Ext.chart.Chart', {    renderTo: Ext.getBody(),    width: 500,    height: 300,    animate: true,    store: store,    axes: [{        type: 'Numeric',        position: 'bottom',        fields: ['data'],        label: {            renderer: Ext.util.Format.numberRenderer('0,0')        },        title: 'Sample Values',        grid: true,        minimum: 0    }, {        type: 'Category',        position: 'left',        fields: ['name'],        title: 'Sample Metrics'    }],    series: [{        type: 'bar',        axis: 'bottom',        highlight: true,        tips: {          trackMouse: true,          width: 140,          height: 28,          renderer: function(storeItem, item) {            this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data') + ' views');          }        },        label: {          display: 'insideEnd',            field: 'data',            renderer: Ext.util.Format.numberRenderer('0'),            orientation: 'horizontal',            color: '#333',            'text-anchor': 'middle'        },        xField: 'name',        yField: 'data'    }]});Ext.MessageBox.confirm('Confirm Download', 'Would you like to download the chart as an image?', function(choice){    if(choice == 'yes'){        chart.save({            type: 'image/png',            filename:'testfile'        });    }});});</script>


 

Cross-browser Processing

I think there may be a problem. Earlier IE versions only support vml plotting. Can I export images in IE versions?

In fact, you don't have to worry about it. Extjs has helped us deal with it. Even in these versions of IE, the data transmitted to the server is also in svg format.

(In addition, if you want to pass in your own defined parameters, such as filename, directly from save, you can consider passing in the call url)

 

Related Article

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.