关于好多需要做结果分析的web应用,结果分析是各种图形展示,譬如饼状图,柱状图,雷达图等等,譬如highcharts,生成图片后如何导出到word中。
正题:如果你用过highcharts,你会发现,直接把生成图的数据传到highcharts接口中即可生成自动生成好看的各种图形。如何把图片导出到word中呢?网上找了好多也没有具体的实施方案。现在粘出来我的代码!
实现步骤:图片生成----其实图片的生成就是把分析的数据算出来,传到前台的highcharts接口中去,并声明生成图形的样式即可:
------图片导出:web上生成的其实不是图片,是一个SVG文件,SVG是一个xml串。这样就好说了,只要把这个xml获取出来,并解析成图片就行了。
代码
-------------前台获取svg---------------------------------
var svgStr = chart.getSVG(); ---------------这是js获取svg串的方法 传到后台。
-----------这是后台-------------------------这需要doxia相关jar包的引入
public void expotResultExcel() throws SysException {
String svg = request.getParameter("svg");
String realpath = ServletActionContext.getServletContext()-------------------这三行是另存为时候使用的
.getRealPath("/themes/default/ExportToWord/");
realpath = realpath + "\\ceshi.doc";
String realpath="D:/ceshi.doc";
InvestigationController.SvgPngConverter.convertToPng(svg, realpath);
}
public static class SvgPngConverter {
/**
* @Description: 将svg字符串转换为png
* @param svgCode
* svg代码
* @param pngFilePath
* 保存的路径
* @throws IOException
* io异常
* @throws TranscoderException
* svg代码异常
*/
public static void convertToPng(String svgCode, String pngFilePath) {
File file = new File(pngFilePath);
// FileOutputStream outputStream = null;
Document document = new Document(PageSize.A4);
// 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
// ByteArrayOutputStream bo=new ByteArrayOutputStream();
try {
RtfWriter2.getInstance(document, new FileOutputStream(file));
document.open();
// file.createNewFile ();
// outputStream = new FileOutputStream (file);
// convertToPng (svgCode, array);
String svgEmp[] = svgCode.split("&");
for (int i = 0; i < svgEmp.length; i++) {
ByteArrayOutputStream array = new ByteArrayOutputStream();
byte[] bytes = svgEmp[i].getBytes("UTF-8");
PNGTranscoder t = new PNGTranscoder();
TranscoderInput input = new TranscoderInput(
new ByteArrayInputStream(bytes));
TranscoderOutput output = new TranscoderOutput(array);
t.transcode(input, output);
byte[] b = array.toByteArray();
// 添加图片 Image.getInstance即可以放路径又可以放二进制字节流
Image img = null;
try {
img = Image.getInstance(b);
img.setAbsolutePosition(0, 0);
img.setAlignment(Image.RECTANGLE);// 设置图片显示位置
// img.scaleAbsolute(690, 400);// 直接设定显示尺寸
img.scalePercent(65);// 表示显示的大小为原尺寸的50%
// img.scalePercent(25, 12);//图像高宽的显示比例
// img.setRotation(30);//图像旋转一定角度
document.add(img);
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
document.close();
} catch (TranscoderException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
}
}
}
这样就把图片导入到ceshi.doc文件中了。大功告成!
2 这样虽然直接导出到d盘中了 但是在linux操作系统中没有D盘肿么办呢?这样就需要另存为的功能了
我也是第一次做另存为 不太了解怎么做,遇到了问题,后来询问得到一种方法,可以吧ceshi.doc上传到服务器,固定存放路径,然后用window.location.href指向该路径即可。
3.这样算是完成大部分了,现在自动另存为的默认名称是“cdshi.doc” 如果要显示中文名称怎么办呢?
在工程的服务中找到server.xml
中设置编码格式位UTF-8即可。