前面說到前台呈現的頁面是img標簽,因此需要在后台生成相應的圖片,在img的src內容中改為相應的路徑地址;而在生成文檔的過程中需要替換相應的img標簽。后一部分上篇文章已經講過,本片主要講前一部分。
為了先在服務器中生成相應的餅圖,我在項目中引用了jfreechart來生成圖表的圖片:
代碼實現:
//content是前台呈現的html內容 content.append("<p style=\"text-align:center\"><img src=\"" + request.getContextPath() + "/exportWord/" + createChartImg("",cycleMap,new Font("宋體", Font.BOLD, 15),sessionId+"階段") + "\"/></p>"); private String createChartImg(String title, Map<String,Double> datas, Font font,String name) throws Exception{ String imgName = name + ".png";//生成圖片名稱 //如果不使用Font,中文將顯示不出來 DefaultPieDataset pds = new DefaultPieDataset(); //獲取迭代器: Iterator iterator= datas.entrySet().iterator(); Map.Entry entry=null; while(iterator.hasNext()){ entry=(Map.Entry) iterator.next(); pds.setValue(entry.getKey().toString(),Double.parseDouble(entry.getValue().toString())); } /** * 生成一個餅圖的圖表 * 分別是:顯示圖表的標題、需要提供對應圖表的DateSet對象、是否顯示圖例、是否生成貼士以及是否生成URL鏈接 */ JFreeChart chart = ChartFactory.createPieChart(title, pds, false, false, true); //得到圖塊 PiePlot plot = (PiePlot) chart.getPlot(); //設置標簽字體、背景顏色 plot.setLabelFont(font); plot.setLabelBackgroundPaint(new Color(51, 199, 226)); //設置標簽生成器(默認{0}) //{0}:key {1}:value {2}:百分比 {3}:sum plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} {2}")); //圖片背景顏色 plot.setBackgroundPaint(new Color(255, 255, 255)); //將內存中的圖片寫到本地硬盤 ChartUtilities.saveChartAsJPEG(new File(ExportWord.getWordPath() + imgName), chart, 400, 200); return imgName; }
最終前台呈現效果:
當然,jfreechart不止能生成餅圖的圖片,還能生成柱狀圖、折線圖等等,本次需求只需要實現餅圖,以后有機會繼續探索!