Java根據word模板生成word文檔之後臺解析和實現及部分代碼(三)D

現在貼出我封裝了的jfreechar工具類,可以根據自己的要求去擴展和封裝,大概封裝了一下:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.RenderingHints;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PolarPlot;
import org.jfree.chart.renderer.DefaultPolarItemRenderer;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.TextAnchor;
import org.springframework.stereotype.Component;

/**
 * 通用的生成柱狀圖的方法
 * @author th
 *
 */
@Component
public class CommonStatisticsCreateImagesDao extends ServletUtilities{
	
	/**
	 * 生成多柱狀圖(柱狀圖)
	 * @param imagePath 生成後的圖片路徑
	 * @param imageName 生成後的圖片名稱
	 * @param categoryDataset  生成圖片的數據結構
	 * @param yName  Y座標的展示名稱
	 * @param width  圖片寬度
	 * @param height  圖片高度
	 * @return
	 */
	public boolean creatPic(String imagePath,String imageName,String yName,CategoryDataset categoryDataset, int width,int height){
	       //設置默認寬度和高度
		    if(width == 0)
		    	width = 700;
		    if(height == 0)
		       height = 450;
		    // 圖表標題 
		    // 目錄軸的顯示標籤 x
			// 數值軸的顯示標籤 y
			// 數據集 
			// 圖表方向:水平、垂直 
			// 是否顯示圖例(對於簡單的柱狀圖必須是false) 
			// 是否生成工具 
			// 是否生成URL鏈接  createBarChart
	        JFreeChart jfreechart = ChartFactory.createBarChart3D(imageName, "", yName, categoryDataset, PlotOrientation.VERTICAL, true, true, false);
	        // 設置圖標題的字體重新設置title new Font("宋體", Font.PLAIN, 10)
	    	Font font = new Font("隸書", Font.BOLD, 25); 
	    	TextTitle title = new TextTitle(imageName); 
	    	title.setFont(font); 
	    	jfreechart.setTitle(title); 
	    	
	    	Font labelFont = new Font("黑體", Font.BOLD, 12); 
	    	/* 
	    	* VALUE_TEXT_ANTIALIAS_OFF表示將文字的抗鋸齒關閉, 
	    	* 使用的關閉抗鋸齒後,字體儘量選擇12到14號的宋體字,這樣文字最清晰好看 
	    	*/ 
	    	jfreechart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); 
	    	jfreechart.setTextAntiAlias(true); 
	    	
	    	jfreechart.setBackgroundPaint(Color.white); 
	    	//顯示圖例
	    	jfreechart.getLegend().setItemFont(new Font("黑體", Font.BOLD, 15)); 
	    	// create plot 
	    	CategoryPlot plot = jfreechart.getCategoryPlot(); 
	    	// 設置橫虛線可見 
	    	plot.setRangeGridlinesVisible(true); 
	    	// 虛線色彩 
	    	plot.setRangeGridlinePaint(Color.gray); 

	    	// 數據軸精度 
	    	NumberAxis vn = (NumberAxis) plot.getRangeAxis(); 
	    	vn.setAutoRangeIncludesZero(true); 
	    	DecimalFormat df = new DecimalFormat("#0.00"); 
	    	vn.setNumberFormatOverride(df); // 數據軸數據標籤的顯示格式 
	    	// x軸設置 
	    	CategoryAxis domainAxis = plot.getDomainAxis(); 
	    	domainAxis.setLabelFont(labelFont);// 軸標題 
	    	domainAxis.setTickLabelFont(labelFont);// 軸數值 
	    	// Lable(Math.PI/3.0)度傾斜 
	    	domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI/3.0)); 
	    	domainAxis.setMaximumCategoryLabelWidthRatio(0.5f);// 橫軸上的 Lable 是否完整顯示 

	    	// 設置距離圖片左端距離 
	    	domainAxis.setLowerMargin(0.1); 
	    	// 設置距離圖片右端距離 
	    	domainAxis.setUpperMargin(0.1); 
	    	// 設置 columnKey 是否間隔顯示 
	    	// domainAxis.setSkipCategoryLabelsToFit(true); 

	    	plot.setDomainAxis(domainAxis); 
	    	// 設置柱圖背景色(注意,系統取色的時候要使用16位的模式來查看顏色編碼,這樣比較準確) 
	    	plot.setBackgroundPaint(new Color(255, 255, 204)); 
	    	
	    	
	    	// y軸設置 
	    	ValueAxis rangeAxis = plot.getRangeAxis(); 
	    	rangeAxis.setLabelFont(labelFont); 
	    	rangeAxis.setTickLabelFont(labelFont); 
	    	// 設置最高的一個 Item 與圖片頂端的距離 
	    	rangeAxis.setUpperMargin(0.15); 
	    	// 設置最低的一個 Item 與圖片底端的距離 
	    	rangeAxis.setLowerMargin(0.15); 
	    	plot.setRangeAxis(rangeAxis); 

	    	BarRenderer3D renderer = new BarRenderer3D(); 
	    	// 設置柱子寬度 
	    	renderer.setMaximumBarWidth(0.05); 
	    	// 設置柱子高度 
	    	//renderer.setMinimumBarLength(0.2); 
	    	// 設置柱子邊框顏色 
	    	//renderer.setBaseOutlinePaint(Color.BLACK); 
	    	// 設置柱子邊框可見 
	    	//renderer.setDrawBarOutline(true); 

	    	//設置柱的顏色 
	    	renderer.setSeriesPaint(0, new GradientPaint(0.0F, 0.0F, Color.green, 0.0F, 0.0F, new Color(0, 255, 0)));
	    	renderer.setSeriesPaint(1, new GradientPaint(0.0F, 0.0F, Color.blue, 0.0F, 0.0F, new Color(0, 0, 255)));
		    renderer.setSeriesPaint(2, new GradientPaint(0.0F, 0.0F, Color.yellow, 0.0F, 0.0F, new Color(255, 255, 0)));
		    renderer.setSeriesPaint(3, new GradientPaint(0.0F, 0.0F, Color.orange, 0.0F, 0.0F, new Color(255, 200, 0)));
		    renderer.setSeriesPaint(4, new GradientPaint(0.0F, 0.0F, Color.red, 0.0F, 0.0F, new Color(255, 0, 0)));

	    	// 設置每個地區所包含的平行柱的之間距離 
	    	//renderer.setItemMargin(0.2); 

	    	// 顯示每個柱的數值,並修改該數值的字體屬性 
	    	renderer.setIncludeBaseInRange(true); 
	    	renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); 
	    	renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));//CENTER_RIGHT
	    	renderer.setBaseItemLabelsVisible(true); 
	    	plot.setRenderer(renderer);
	    	// 設置柱的透明度 
	    	plot.setForegroundAlpha(1.0f); 
	      
	        //生成水印類似
//	        CategoryTextAnnotation categorytextannotation = new CategoryTextAnnotation("Minimum grade to pass", "Robert", 0.70999999999999996D);
//	        categorytextannotation.setCategoryAnchor(CategoryAnchor.START);
//	        categorytextannotation.setFont(new Font("SansSerif", 0, 12));
//	        categorytextannotation.setTextAnchor(TextAnchor.BOTTOM_LEFT);
//	        categoryplot.addAnnotation(categorytextannotation);
	        
	        FileOutputStream fos_jpg = null; 
	    	try{
		    	fos_jpg = new FileOutputStream(imagePath); 
		    	ChartUtilities.writeChartAsPNG(fos_jpg,jfreechart,width,height); 
	    	}catch (Exception e) { 
	    		e.printStackTrace(); 
	    		return false; 
	    	}finally{ 
	    	try{ 
		    	fos_jpg.close(); 
		    	System.out.println("create pie-chart.柱狀圖創建成功!!!"); 
	    	}catch (Exception e){ 
	    		e.printStackTrace(); 
	    	  } 
	    	} 
	    	return true;
	    }

	 /**
		 * 生成(曲線圖片)
		 * @param imagePath 生成後的圖片路徑
		 * @param imageName 生成後的圖片名稱
		 * @param categoryDataset  生成圖片的數據結構
		 * @param yName  Y座標的展示名稱
		 * @param width  圖片寬度
		 * @param height  圖片高度
		 * @return
		 */
		 public boolean createLinePic(String imagePath,String imageName,String yName,CategoryDataset categoryDataset, int width,int height){
			    //設置默認寬度和高度
			    if(width == 0)
			    	width = 700;
			    if(height == 0)
			       height = 450;
			    JFreeChart jfreechart = ChartFactory.createLineChart(imageName, null, yName, categoryDataset, PlotOrientation.VERTICAL, false, true, false);
		        //jfreechart.addSubtitle(new TextTitle("Number of Classes By Release"));
		        //TextTitle texttitle = new TextTitle("Source: Java In A Nutshell (5th Edition) by David Flanagan (O'Reilly)");
		        /*texttitle.setFont(new Font("SansSerif", 0, 10));
		        texttitle.setPosition(RectangleEdge.BOTTOM);
		        texttitle.setHorizontalAlignment(HorizontalAlignment.RIGHT);
		        jfreechart.addSubtitle(texttitle);*/
		        CategoryPlot categoryplot = (CategoryPlot)jfreechart.getPlot();
		        categoryplot.setRangePannable(true);
		        categoryplot.setRangeGridlinesVisible(false);
		      
		        NumberAxis numberaxis = (NumberAxis)categoryplot.getRangeAxis();
		        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
		        ChartUtilities.applyCurrentTheme(jfreechart);
		        LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer)categoryplot.getRenderer();
		        lineandshaperenderer.setBaseShapesVisible(true);
		        lineandshaperenderer.setDrawOutlines(true);
		        lineandshaperenderer.setUseFillPaint(true);
		        lineandshaperenderer.setBaseFillPaint(Color.white);
		        lineandshaperenderer.setSeriesStroke(0, new BasicStroke(3F));
		        lineandshaperenderer.setSeriesOutlineStroke(0, new BasicStroke(2.0F));
		        lineandshaperenderer.setSeriesShape(0, new java.awt.geom.Ellipse2D.Double(-5D, -5D, 10D, 10D));
		        
		        /*-------------處理亂碼-------------------*/
		        Font font = new Font("隸書", Font.BOLD, 25); 
		    	TextTitle title = new TextTitle(imageName); 
		    	title.setFont(font); 
		    	jfreechart.setTitle(title); 
		    	
		    	Font labelFont = new Font("黑體", Font.BOLD, 12); 
		        
				CategoryAxis categoryAxis =  categoryplot.getDomainAxis();
				categoryAxis.setLabelFont(labelFont);
				categoryAxis.setTickLabelFont(labelFont);
				ValueAxis valueAxis =  categoryplot.getRangeAxis();
				valueAxis.setLabelFont(labelFont);
				CategoryAxis categoryAxis2 =  categoryplot.getDomainAxis();
				categoryAxis2.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(0.66666));
			    
		        FileOutputStream fos_jpg = null; 
		    	try{
			    	fos_jpg = new FileOutputStream(imagePath); 
			    	ChartUtilities.writeChartAsPNG(fos_jpg,jfreechart,width,height); 
		    	}catch (Exception e) { 
		    		e.printStackTrace(); 
		    		return false; 
		    	}finally{ 
		    	try{ 
			    	fos_jpg.close(); 
			    	System.out.println("create line-chart.曲線圖創建成功!!!"); 
		    	}catch (Exception e){ 
		    		e.printStackTrace(); 
		    	  } 
		    	} 
		    	return true;
		    }
		 
		   /**
			 * 生成(餅狀圖片)
			 * @param imagePath 生成後的圖片路徑
			 * @param imageName 生成後的圖片名稱
			 * @param categoryDataset  生成圖片的數據結構
			 * @param 
			 * @param width  圖片寬度
			 * @param height  圖片高度
			 * @return
			 */
			 @SuppressWarnings("deprecation")
			public boolean createPiePic(String imagePath,String imageName,PieDataset categoryDataset, int width,int height){
				    //設置默認寬度和高度
				    if(width == 0)
				    	width = 700;
				    if(height == 0)
				       height = 450;
			        
				    
				    JFreeChart jfreechart = ChartFactory.createPieChart(imageName, categoryDataset, true, true, false);
				   
				    // 設置圖標題的字體重新設置title new Font("宋體", Font.PLAIN, 10)
			    	Font font = new Font("隸書", Font.BOLD, 25); 
			    	TextTitle title = new TextTitle(imageName); 
			    	title.setFont(font); 
			    	jfreechart.setTitle(title); 
			    	
			    	/* 
			    	* VALUE_TEXT_ANTIALIAS_OFF表示將文字的抗鋸齒關閉, 
			    	* 使用的關閉抗鋸齒後,字體儘量選擇12到14號的宋體字,這樣文字最清晰好看 
			    	*/ 
			    	jfreechart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); 
			    	jfreechart.setTextAntiAlias(true); 
			    	
			    	jfreechart.setBackgroundPaint(Color.white); 
			    	jfreechart.getLegend().setItemFont(new Font("宋體", Font.PLAIN, 15)); 
			    	
			    	title.setToolTipText("A title tooltip!");
			    	
			        PiePlot pieplot = (PiePlot)jfreechart.getPlot();
			        pieplot.setLabelFont(new Font("黑體",Font.PLAIN,15));
			        pieplot.setNoDataMessage("No data available");
			        
			        pieplot.setCircular(false);
			        pieplot.setLabelGap(0.02D);
			        jfreechart.getLegend().setItemFont(new Font("黑體",Font.BOLD,15));
			        pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator( 
			        		"{2}", NumberFormat.getNumberInstance(), 
			        		new DecimalFormat("0.00%"))); 
			        		// 圖例顯示百分比:自定義方式, {0} 表示選項, {1} 表示數值, {2} 表示所佔比例 
			       /* pieplot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator( 
			    	"{0}={1}({2})")); */
			        
			        //餅狀圖的顏色定義
			        pieplot.setSectionPaint(0, new GradientPaint(0.0F, 0.0F, Color.green, 0.0F, 0.0F, new Color(0, 255, 0)));
			    	pieplot.setSectionPaint(1, new GradientPaint(0.0F, 0.0F, Color.blue, 0.0F, 0.0F, new Color(0, 0, 255)));
			    	pieplot.setSectionPaint(2, new GradientPaint(0.0F, 0.0F, Color.yellow, 0.0F, 0.0F, new Color(255, 255, 0)));
			    	pieplot.setSectionPaint(3, new GradientPaint(0.0F, 0.0F, Color.orange, 0.0F, 0.0F, new Color(255, 200, 0)));
			    	pieplot.setSectionPaint(4, new GradientPaint(0.0F, 0.0F, Color.red, 0.0F, 0.0F, new Color(255, 0, 0)));
			        
			        
			        
			        /*-------------處理亂碼-------------------*/
			        
			        FileOutputStream fos_jpg = null; 
			    	try{
				    	fos_jpg = new FileOutputStream(imagePath); 
				    	ChartUtilities.writeChartAsPNG(fos_jpg,jfreechart,width,height); 
			    	}catch (Exception e) { 
			    		e.printStackTrace(); 
			    		return false; 
			    	}finally{ 
			    	try{ 
				    	fos_jpg.close(); 
				    	System.out.println("create pie-chart.餅狀圖創建成功!!!"); 
			    	}catch (Exception e){ 
			    		e.printStackTrace(); 
			    	  } 
			    	} 
			    	return true;
			    }
			 
			 
			 
			 
			 /**
				 * 生成(雷達圖)
				 * @param imagePath 生成後的圖片路徑
				 * @param imageName 生成後的圖片名稱
				 * @param xydataset  生成圖片的數據結構
				 * @param width  圖片寬度
				 * @param height  圖片高度
				 * @param pplotArr  PolarPlot數組圖例名字(生成圖例的 可有可無)
				 * @return
				 */ 
			 public boolean createPolarChart(String imagePath,String imageName,XYDataset xydataset, int width,int height,String[] pplotArr){
		  
				    //設置默認寬度和高度
				    if(width == 0)
				    	width = 700;
				    if(height == 0)
				       height = 450;
				    
			        JFreeChart jfreechart = ChartFactory.createPolarChart(imageName, xydataset, true, false, false);
			        PolarPlot polarplot = (PolarPlot)jfreechart.getPlot();
//			        if(pplotArr != null && pplotArr.length > 0){
//			        	for (int i = 0; i < pplotArr.length; i++) {
//			        		polarplot.addCornerTextItem(pplotArr[i]);
//						}
//			        }
			        polarplot.setAngleGridlinePaint(Color.white);
			        polarplot.setRadiusGridlinePaint(Color.white);
			        NumberAxis numberaxis = (NumberAxis)polarplot.getAxis();
			        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
			        ChartUtilities.applyCurrentTheme(jfreechart);
			       
			        //顯示網格度數
			        polarplot.setAngleGridlinesVisible(false);
			        
			        // 設置雷達顏色
			        GradientPaint gradientpaint3 = new GradientPaint(0.0F, 0.0F,
			          Color.black, 0.0F, 0.0F, Color.black);
			        polarplot.setRadiusGridlinePaint(gradientpaint3);//
		
			        // 兩個四邊形顏色
			        GradientPaint gradientpaint1 = new GradientPaint(0.0F, 0.0F, Color.red,
			          0.0F, 0.0F, Color.red); //
			        GradientPaint gradientpaint2 = new GradientPaint(0.0F, 0.0F,
			          Color.blue, 0.0F, 0.0F, Color.blue); //
			        // 設置兩個四邊形顏色
			        DefaultPolarItemRenderer renderer = new DefaultPolarItemRenderer();
			        renderer.setSeriesPaint(0, gradientpaint1);
			        renderer.setSeriesPaint(1, gradientpaint2);
			        renderer.setItemLabelFont(new Font("黑體", Font.BOLD, 15));
			        renderer.setItemLabelsVisible(true);

			        polarplot.setRenderer(renderer);
		
			        numberaxis.setAutoRange(true);
			        //numberaxis.setVisible(false);
			        //numberaxis.setTickUnit(new NumberTickUnit(2));// 設置雷達網格數量
			        
			        // 設置說明的字體
			        jfreechart.getTitle().setFont(new Font("隸書", Font.BOLD, 25));
			        
			    	/* 
			    	* VALUE_TEXT_ANTIALIAS_OFF表示將文字的抗鋸齒關閉, 
			    	* 使用的關閉抗鋸齒後,字體儘量選擇12到14號的宋體字,這樣文字最清晰好看 
			    	*/ 
			    	jfreechart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); 
			    	jfreechart.setTextAntiAlias(true); 
			    	
			    	jfreechart.setBackgroundPaint(Color.white); 
			    	//顯示圖例
			    	jfreechart.getLegend().setItemFont(new Font("黑體", Font.BOLD, 15)); 
			        
			        
			        FileOutputStream fos_jpg = null; 
			        
			    	try{
				    	fos_jpg = new FileOutputStream(imagePath); 
				    	ChartUtilities.writeChartAsPNG(fos_jpg,jfreechart,width,height); 
			    	}catch (Exception e) { 
			    		e.printStackTrace(); 
			    		return false; 
			    	}finally{ 
			    	try{ 
				    	fos_jpg.close(); 
				    	System.out.println("create pie-chart.雷達圖創建成功!!!"); 
			    	}catch (Exception e){ 
			    		e.printStackTrace(); 
			    	  } 
			    	} 
			    	return true;
			    }
	
}


未完待續


發佈了36 篇原創文章 · 獲贊 18 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章