將FusionCharts導出為圖片、PDF、Excel


本文轉自互聯網

本文的思路:

(1)准備一個Java Web項目

(2)將FusionCharts加入到項目

(3)將FusionChart輸出為圖片、PDF、Excel

 

環境:

操作系統:Windows 8.1 企業版

開發環境:MyEclipse 2015 Stable 2.0

 

1、准備JavaWeb項目

FusionCharts可以接受JSON、XML類型的數據,而JSON類型的數據相對比較簡單,因此我們准備的JavaWeb項目能夠提供返回JSON數據的能力。

 

1.1、新建Web Project

添加一個Web Project,項目名稱設置為“oa”。

wKioL1fKzX6jeVxlAAepPTHhFAI763.gif

 

項目下的文件目錄結構:

wKiom1fK1MXzYCh9AAAVjCtL384626.png

 

1.2、添加ChartData.java文件

放置到src目錄內的com.rk.entity包下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package  com.rk.entity;
 
import  java.util.ArrayList;
import  java.util.List;
 
public  class  ChartData {
     private  String label;
     private  Object value;
     
     public  ChartData() {
     }
     public  ChartData(String label, Object value) {
         this .label = label;
         this .value = value;
     }
 
     public  static  List<ChartData> getExample(){
         List<ChartData> list =  new  ArrayList<ChartData>();
         list.add( new  ChartData( "Jan" "420000" ));
         list.add( new  ChartData( "Feb" "810000" ));
         list.add( new  ChartData( "Mar" "720000" ));
         list.add( new  ChartData( "Apr" "550000" ));
         list.add( new  ChartData( "May" "910000" ));
         list.add( new  ChartData( "Jun" "510000" ));
         list.add( new  ChartData( "Jul" "680000" ));
         list.add( new  ChartData( "Aug" "620000" ));
         list.add( new  ChartData( "Sep" "610000" ));
         list.add( new  ChartData( "Oct" "490000" ));
         list.add( new  ChartData( "Nov" "900000" ));
         list.add( new  ChartData( "Dec" "730000" ));
         return  list;
     }
     
     public  String getLabel() {
         return  label;
     }
     public  void  setLabel(String label) {
         this .label = label;
     }
     public  Object getValue() {
         return  value;
     }
     public  void  setValue(Object value) {
         this .value = value;
     }
     @Override
     public  String toString() {
         return  "Chart [label="  + label +  ", value="  + value +  "]" ;
     }
}

 

1.3、添加轉換JSON的工具類

(1)添加gson-2.6.2.jar到WebRoot/WEB-INF/lib目錄下

(2)在com.rk.utils包下添加JsonResult.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package  com.rk.utils;
 
import  com.google.gson.Gson;
import  com.google.gson.GsonBuilder;
 
public  class  JsonResult {
     private  String status;
     private  Object data;
     public  String getStatus() {
         return  status;
     }
     public  void  setStatus(String status) {
         this .status = status;
     }
     public  Object getData() {
         return  data;
     }
     public  void  setData(Object data) {
         this .data = data;
     }
     @Override
     public  String toString() {
         Gson gson =  new  GsonBuilder().create();
         return  gson.toJson( this );
     }
     
}

 

1.4、添加Servlet

(1)在com.rk.web包下添加JsonDataServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package  com.rk.web;
 
import  java.io.IOException;
import  java.util.List;
 
import  javax.servlet.ServletException;
import  javax.servlet.ServletOutputStream;
import  javax.servlet.http.HttpServlet;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;
 
import  com.rk.entity.ChartData;
import  com.rk.utils.JsonResult;
 
public  class  JsonDataServlet  extends  HttpServlet {
 
     @Override
     protected  void  doGet(HttpServletRequest request, HttpServletResponse response)  throws  ServletException, IOException {
         this .doPost(request, response);
     }
 
     @Override
     protected  void  doPost(HttpServletRequest request, HttpServletResponse response)  throws  ServletException, IOException {
         //1、設置輸出格式為JSON
         response.setContentType( "application/json;charset=utf-8" );
         //2、輸出
         //2.1、准備JSON數據
         List<ChartData> list = ChartData.getExample();
         JsonResult result =  new  JsonResult();
         result.setStatus( "ok" );
         result.setData(list);
         String strJson = result.toString();
         //2.2、輸出JSON數據
         ServletOutputStream outputStream = response.getOutputStream();
         outputStream.write(strJson.getBytes( "utf-8" ));
     }
}

(2)在web.xml中對JsonDataServlet類進行注冊

1
2
3
4
5
6
7
8
< servlet >
     < servlet-name >JsonDataServlet</ servlet-name >
     < servlet-class >com.rk.web.JsonDataServlet</ servlet-class >
</ servlet >
< servlet-mapping >
     < servlet-name >JsonDataServlet</ servlet-name >
     < url-pattern >/getJsonData</ url-pattern >
</ servlet-mapping >

完整的web.xml文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< web-app  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"  xmlns = "http://java.sun.com/xml/ns/javaee"  xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  id = "WebApp_ID"  version = "3.0" >
   < display-name >oa</ display-name >
   < welcome-file-list >
     < welcome-file >index.jsp</ welcome-file >
   </ welcome-file-list >
  
     < servlet >
         < servlet-name >JsonDataServlet</ servlet-name >
         < servlet-class >com.rk.web.JsonDataServlet</ servlet-class >
     </ servlet >
     < servlet-mapping >
         < servlet-name >JsonDataServlet</ servlet-name >
         < url-pattern >/getJsonData</ url-pattern >
     </ servlet-mapping >
</ web-app >

 

1.5、測試返回JSON數據是否正常

訪問地址:

1
http://127.0.0.1:8080/oa/getJsonData

如果能夠返回JSON數據,則表示 正常

效果圖

wKioL1fK0wHC3M00AAG8ZYOvrsk604.gif

 

 

2、將FusionCharts加入到JavaWeb項目中

 

2.1、准備index.jsp

將原有的index.jsp修改一下,HTML代碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html >
   < head >
     < title >統計圖表</ title >
     < meta  http-equiv = "pragma"  content = "no-cache" >
     < meta  http-equiv = "cache-control"  content = "no-cache" >
     < meta  http-equiv = "expires"  content = "0" >    
   </ head >
   
   < body >
     < div  id = "chartContainer" >FusionCharts XT will load here!</ div >
   </ body >
</ html >

 

2.2、添加js文件到項目當中

添加以下4個js文件到項目WebRoot/js目錄下

jquery-1.12.3.js

fusioncharts.charts.js

fusioncharts.js

fusioncharts.theme.fint.js

目錄結構圖如下:

wKioL1fK1eez_TrSAAAVhoc1hwY555.png

 

2.3、將js文件引入到index.jsp文件中

1
2
3
< script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/jquery/jquery-1.12.3.js" ></ script >    
< script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/fusioncharts/fusioncharts.js" ></ script >    
< script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/fusioncharts/themes/fusioncharts.theme.fint.js" ></ script >

完整的index.jsp如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html >
   < head >
     < title >統計圖表</ title >
     < meta  http-equiv = "pragma"  content = "no-cache" >
     < meta  http-equiv = "cache-control"  content = "no-cache" >
     < meta  http-equiv = "expires"  content = "0" >
     < script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/jquery/jquery-1.12.3.js" ></ script >    
     < script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/fusioncharts/fusioncharts.js" ></ script >    
     < script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/fusioncharts/themes/fusioncharts.theme.fint.js" ></ script >    
   </ head >
   
   < body >
     < div  id = "chartContainer" >FusionCharts XT will load here!</ div >
   </ body >
</ html >

 

2.4、使用jQuery AJAX獲取數據,並渲染FusionCharts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
     <script type= "text/javascript" >
         //頁面加載完成后,從服務器獲取數據
         $(document).ready( function (){
             $.ajax({
                 url: "${pageContext.request.contextPath}/getJsonData" ,
                 type: "post" ,
                 dataType: "json" ,
                 success: function (result){
                     if (result.status ==  "ok" ){ displayFusionChart(result.data); }
                     else { alert( "數據出錯!" ); }
                 },
                 error: function (){ alert( "AJAX通信失敗!" ); }
             });
         });
         //顯示FusionCharts
         function  displayFusionChart(chartData){
             var  revenueChart =  new  FusionCharts({
                 "type" "column2d" ,
                 "renderAt" "chartContainer" ,
                 "width" "500" ,
                 "height" "300" ,
                 "dataFormat" "json" ,
                 "dataSource" : {
                   "chart" : {
                       "caption" "Monthly revenue for last year" ,
                       "subCaption" "Harry's SuperMart" ,
                       "xAxisName" "Month" ,
                       "yAxisName" "Revenues (In USD)" ,
                       "theme" "fint"
                    },
                   "data" : chartData
                 }
             });
 
             revenueChart.render();
         }
     </script>

 

完整的index.jsp如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html >
   < head >
     < title >統計圖表</ title >
     < meta  http-equiv = "pragma"  content = "no-cache" >
     < meta  http-equiv = "cache-control"  content = "no-cache" >
     < meta  http-equiv = "expires"  content = "0" >
     < script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/jquery/jquery-1.12.3.js" ></ script >    
     < script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/fusioncharts/fusioncharts.js" ></ script >    
     < script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/fusioncharts/themes/fusioncharts.theme.fint.js" ></ script >
     < script  type = "text/javascript" >
         //頁面加載完成后,從服務器獲取數據
         $(document).ready(function(){
             $.ajax({
                 url:"${pageContext.request.contextPath}/getJsonData",
                 type:"post",
                 dataType:"json",
                 success:function(result){
                     if(result.status == "ok"){ displayFusionChart(result.data); }
                     else{ alert("數據出錯!"); }
                 },
                 error:function(){ alert("AJAX通信失敗!"); }
             });
         });
         //顯示FusionCharts
         function displayFusionChart(chartData){
             var revenueChart = new FusionCharts({
                 "type": "column2d",
                 "renderAt": "chartContainer",
                 "width": "500",
                 "height": "300",
                 "dataFormat": "json",
                 "dataSource": {
                   "chart": {
                       "caption": "Monthly revenue for last year",
                       "subCaption": "Harry's SuperMart",
                       "xAxisName": "Month",
                       "yAxisName": "Revenues (In USD)",
                       "theme": "fint"
                    },
                   "data": chartData
                 }
             });
 
             revenueChart.render();
         }
     </ script >    
   </ head >
   
   < body >
     < div  id = "chartContainer" >FusionCharts XT will load here!</ div >
   </ body >
</ html >

 

2.5、測試FusionCharts是否正常顯示

訪問地址:

1
http://127.0.0.1:8080/oa/index.jsp

如果正常顯示出圖表,則表示 正常。

效果圖如下:

wKioL1fK2QSROyxkAAJxf-Uolk4616.gif

 

 

 

3、將FusionCharts輸出為圖片、PDF、Excel

 

3.1、打開FusionCharts的輸出功能

打開index.jsp文件,在創建FusionCharts對象的chart屬性中添加exportEnabled屬性。

1
2
                       //開啟FusionCharts的輸出功能
                       "exportEnabled" : "1" ,

如下圖:

wKioL1fK2pvB_SxPAABphduMHg8676.png

 

完整的index.jsp如下,可以看下相關的java視頻

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html >
   < head >
     < title >統計圖表</ title >
     < meta  http-equiv = "pragma"  content = "no-cache" >
     < meta  http-equiv = "cache-control"  content = "no-cache" >
     < meta  http-equiv = "expires"  content = "0" >
     < script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/jquery/jquery-1.12.3.js" ></ script >    
     < script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/fusioncharts/fusioncharts.js" ></ script >    
     < script  type = "text/javascript"  src = "${pageContext.request.contextPath}/js/fusioncharts/themes/fusioncharts.theme.fint.js" ></ script >
     < script  type = "text/javascript" >
         //頁面加載完成后,從服務器獲取數據
         $(document).ready(function(){
             $.ajax({
                 url:"${pageContext.request.contextPath}/getJsonData",
                 type:"post",
                 dataType:"json",
                 success:function(result){
                     if(result.status == "ok"){ displayFusionChart(result.data); }
                     else{ alert("數據出錯!"); }
                 },
                 error:function(){ alert("AJAX通信失敗!"); }
             });
         });
         //顯示FusionCharts
         function displayFusionChart(chartData){
             var revenueChart = new FusionCharts({
                 "type": "column2d",
                 "renderAt": "chartContainer",
                 "width": "500",
                 "height": "300",
                 "dataFormat": "json",
                 "dataSource": {
                   "chart": {
                       "caption": "Monthly revenue for last year",
                       "subCaption": "Harry's SuperMart",
                       "xAxisName": "Month",
                       "yAxisName": "Revenues (In USD)",
                       //開啟FusionCharts的輸出功能
                       "exportEnabled":"1",
                       "theme": "fint"
                    },
                   "data": chartData
                 }
             });
 
             revenueChart.render();
         }
     </ script >    
   </ head >
   
   < body >
     < div  id = "chartContainer" >FusionCharts XT will load here!</ div >
   </ body >
</ html >

 

3.2、重新訪問index.jsp,查看輸出功能

 

在聯網的情況下,是如下效果

wKioL1fK3vDxYqaYAASuQ5Q4RLw196.gif

 

在不聯網的情況下,是如下效果

wKiom1fK3xaxGnThAALOZv3x1wI903.gif

 

 

原文地址:http://www.fusioncharts.com/dev/exporting-charts/exporting-charts-as-image-and-pdf.html

 

FusionCharts Suite XT uses JavaScript to render charts in the browser using SVG and VML. A prominent feature is the ability to export the rendered charts in the JPG, PNG, SVG, and PDF formats.

The export is done using a server-side helper library that converts the SVG to the required format. VML can also be exported as it is converted to SVG internally before exporting. During the export process, the data to be exported is sent to the FusionCharts servers for processing and generating the output in the required format.

You must have an active internet connection for this feature to work.

To enable server-side exporting, the chart level attribute exportEnabled is set to 1. The  menu button is then visible in the top-right corner of the chart. Click/hover over this menu button to see the dropdown menu with the export options, as shown in the image below:

 

 

 

You must have an active internet connection for this feature to work.

 

通過上面這句話,我們可以得知,這需要在聯網的情況下才能使用導出圖片、PDF的功能。

 

但是,我們並不會止步如此,我們的目標是即使在不聯網的情況也能夠導出圖片、PDF、Excel。

 

3.3、不聯網的情況下,輸出圖片、PDF、Excel

(1)安裝InkscapeImageMagick

Inkscape的下載地址:https://inkscape.org/zh/download/windows/

wKioL1fK44fAKx-wAAEJ7XeWiUA978.png我的電腦是64位的,因此選擇了64-bit Windows installer(msi)

 

 

ImageMagick的下載地址:http://www.imagemagick.org/script/binary-releases.php

wKiom1fK49Oyc7HSAAEYIo83c0k308.png

同樣,我也選擇了x64版本的下載

 

(2)引入jar包

拷貝fusioncharts-suite-xt/export-handlers/java-export-handler目錄下的fcexporter.jar到WebRoot/WEB-INF/lib目錄下

wKiom1fK5LGyytSqAAF5qZFMF3I411.gif

 

(3)在web.xml對jar包中的Servlet類進行注冊和映射

1
2
3
4
5
6
7
8
9
10
< servlet >
     < display-name >FCExporter</ display-name >
     < servlet-name >FCExporter</ servlet-name >
     < servlet-class >com.fusioncharts.exporter.servlet.FCExporter</ servlet-class >
     < load-on-startup >1</ load-on-startup >
</ servlet >
< servlet-mapping >
     < servlet-name >FCExporter</ servlet-name >
     < url-pattern >/exportFusionCharts</ url-pattern >
</ servlet-mapping >   

 

對於url-pattern部分,我們可以自定義(后面會用到這個url-pattern)

wKiom1fMjL-zs4EJAAA_h06YIy0612.png

 

完整的web.xml如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< web-app  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"  xmlns = "http://java.sun.com/xml/ns/javaee"  xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  id = "WebApp_ID"  version = "3.0" >
   < display-name >oa</ display-name >
   < welcome-file-list >
     < welcome-file >index.jsp</ welcome-file >
   </ welcome-file-list >
  
     < servlet >
         < servlet-name >JsonDataServlet</ servlet-name >
         < servlet-class >com.rk.web.JsonDataServlet</ servlet-class >
     </ servlet >
     < servlet-mapping >
         < servlet-name >JsonDataServlet</ servlet-name >
         < url-pattern >/getJsonData</ url-pattern >
     </ servlet-mapping >
 
     < servlet >
         < display-name >FCExporter</ display-name >
         < servlet-name >FCExporter</ servlet-name >
         < servlet-class >com.fusioncharts.exporter.servlet.FCExporter</ servlet-class >
         < load-on-startup >1</ load-on-startup >
     </ servlet >
     < servlet-mapping >
         < servlet-name >FCExporter</ servlet-name >
         < url-pattern >/exportFusionCharts</ url-pattern >
     </ servlet-mapping >   
 
</ web-app >

 

 

 

通過配置,我們逆向推理,在jar當中應該是一個Servlet類。

我們可以通過jd-gui軟件對該jar包進行反編譯,如下圖

wKioL1fMjFCS6GHzAABZ1L5B5Co309.png

 

 

 

 

(4)(在后台)對jar包進行配置

在src目錄下添加fusioncharts_export.properties文件,內容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Please specify the path to a folder with write permissions
# The exported image/PDF files would be saved here (for Linux based server SAVEPATH should be changed to relative or absolute path accordingly)
SAVEPATH = /JSP/ExportExample/ExportedImages/
 
# This constant HTTP_URI stores the HTTP reference to
# the folder where exported charts will be saved.
# Please enter the HTTP representation of that folder
# in this constant e.g., http://www.yourdomain.com/images/
HTTP_URI = http://localhost:8081/ExportHandler/JSP/ExportExample/ExportedImages/
 
# OVERWRITEFILE sets whether the export handler would overwrite an existing file
# the newly created exported file. If it is set to false the export handler would
# not overwrite. In this case if INTELLIGENTFILENAMING is set to true the handler
# would add a suffix to the new file name. The suffix is a randomly generated UUID.
# Additionally, you can add a timestamp or random number as additional prefix.
FILESUFFIXFORMAT = TIMESTAMP
OVERWRITEFILE = false
INTELLIGENTFILENAMING = true
 
# Set the path of Inkscape here(Only for Windows)
INKSCAPE_PATH = C\:\\Program Files\\Inkscape
 
# Set the path of ImageMagick here(Only for Windows)
IMAGEMAGICK_PATH =C\:\\Program Files\\ImageMagick-7.0.2-Q16

其中,INKSCAPE_PATHIMAGEMAGICK_PATH要寫成實際安裝文件的路徑(其余的值,我未做修改,因為不太清楚是做什么用的):

1
2
3
4
5
# Set the path of Inkscape here(Only for Windows)
INKSCAPE_PATH = C\:\\Program Files\\Inkscape
 
# Set the path of ImageMagick here(Only for Windows)
IMAGEMAGICK_PATH =C\:\\Program Files\\ImageMagick-7.0.2-Q16

 

(5)(在前台)對JSP文件進行屬性設置

修改index.jsp文件中創建FusionCharts部分的chart屬性,添加如下內容

1
2
3
                       "exportAtClient":"0",
                       "exportHandler":"http://127.0.0.1:8080/oa/exportFusionCharts",
                       "exportAction":"download",

如下圖:

wKiom1fMjyGQ35hQAACBcGyRQqE007.png這幾個參數的作用如下:

wKioL1fMj06jyWhHAABZ7F0pDBE953.png

(6)再次測試index.jsp,查看輸出結果

注意:在進行測試的時候,如果沒有成功,需要首先清空一下瀏覽器的緩存,再次訪問查看結果。

 

結果如下:

wKioL1fMlPjyTn5dAAqK5myUzsg221.gif

 

在上圖中,我們看到了圖片的來源是http://127.0.0.1:8080 ,說明是從本地產生的圖片,而不是從fusioncharts的官網獲取的圖片。

 

(7)去除水印

在上圖中的左下角,我們可以看到“FusionCharts XT Trial”字樣。如果想去掉它,可以打開fusioncharts.js,然后將 FusionCharts XT Trial 替換為 空字符串。

wKiom1fMltDCGQKdAAE54hTX4Ac242.gif

 

清空瀏覽器緩存,再次訪問index.jsp,可以看到水印不見了。

wKioL1fMlzuiMcS2AAHkOpB5yRI307.gif

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM