前面说到前台呈现的页面是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不止能生成饼图的图片,还能生成柱状图、折线图等等,本次需求只需要实现饼图,以后有机会继续探索!