java后台生成HighCharts图片

[b]在前端通过HighCharts获取svgCode,再根据svgCode生成图片。生成的图片在插入到word文档中 freemarker, BASE64Encoder[/b]

[url]http://www.muxuanli.com:8888/lmx/blog/10[/url]

[b]1. 获取svgCode[/b]

var chart = $("#container").highcharts();
var svgCode = chart.getSVG();


[b]2. 根据svgCode生成图片[/b]


String svgImgPath = uploadFilePathService.getUploadFilePath()+"svg/"+salivaBox.getBarCode()+"_"+m+".png";
String svgCode = svgCodeList.get(m).replace("Highcharts.com.cn","");
SvgPngConverter.convertToPng(svgCode, svgImgPath);
params.put("image"+(m+1), SvgPngConverter.getImageBASE64Encoder(svgImgPath));


[b]3. SvgPngConverter[/b]


import java.io.*;

import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import sun.misc.BASE64Encoder;

/**
* Created by lijie on 17/6/5.
*/
public class SvgPngConverter {

/**
*@Description: 将svg字符串转换为png
*@Author:
*@param svgCode svg代码
*@param pngFilePath 保存的路径
*@throws IOException io异常
*@throws TranscoderException svg代码异常
*/
public static void convertToPng(String svgCode,String pngFilePath) throws IOException,TranscoderException{

File file = new File (pngFilePath);

FileOutputStream outputStream = null;
try {
file.createNewFile ();
outputStream = new FileOutputStream (file);
convertToPng (svgCode, outputStream);
} finally {
if (outputStream != null) {
try {
outputStream.close ();
} catch (IOException e) {
e.printStackTrace ();
}
}
}
}

/**
*@Description: 将svgCode转换成png文件,直接输出到流中
*@param svgCode svg代码
*@param outputStream 输出流
*@throws TranscoderException 异常
*@throws IOException io异常
*/
public static void convertToPng(String svgCode,OutputStream outputStream) throws TranscoderException,IOException{
try {
byte[] bytes = svgCode.getBytes ("UTF-8");
PNGTranscoder t = new PNGTranscoder ();
TranscoderInput input = new TranscoderInput (new ByteArrayInputStream (bytes));
TranscoderOutput output = new TranscoderOutput (outputStream);
t.transcode (input, output);
outputStream.flush ();
} finally {
if (outputStream != null) {
try {
outputStream.close ();
} catch (IOException e) {
e.printStackTrace ();
}
}
}
}

public static String getImageBASE64Encoder(String imagePath) {
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imagePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值