php+batik 实现导出highchart图片功能

最近有个导出需求需要将highchart的图片和数据报表一起生成。
折腾了几天,终于搞定。
1、首先你需要安装JAVA环境。不需要设置环境变量什么的。
2、下载相关的batik jar包,这个我下载了好多次都是错误的。附件里面有我整理好的。
3、调用官方写的PHP程序,我整理成一个函数了。

function svgToImg($type, $svg, $filename){
clearFile(SAVE_PATH);//删除过期文件
ini_set('magic_quotes_gpc', 'off');
$svg = (string) $svg;
$filename = (string) $filename;

// prepare variables
if (!$filename or !preg_match('/^[A-Za-z0-9\-_ ]+$/', $filename)) {
$filename = 'chart';
}
if (get_magic_quotes_gpc()) {
$svg = stripslashes($svg);
}
// check for malicious attack in SVG
if(strpos($svg,"<!ENTITY") !== false || strpos($svg,"<!DOCTYPE") !== false){
exit("Execution is stopped, the posted SVG could contain code for a malicious attack");
}

$tempName = md5(rand());

// allow no other than predefined types
if ($type == 'image/png') {
$typeString = '-m image/png';
$ext = 'png';

} elseif ($type == 'image/jpeg') {
$typeString = '-m image/jpeg';
$ext = 'jpg';

} elseif ($type == 'application/pdf') {
$typeString = '-m application/pdf';
$ext = 'pdf';

} elseif ($type == 'image/svg+xml') {
$ext = 'svg';

} else { // prevent fallthrough from global variables
$ext = 'txt';
}

$outfile = SAVE_PATH.$tempName.'.'.$ext;

if (isset($typeString)) {

// size
$width = '';
if ($_POST['width']) {
$width = (int)$_POST['width'];
if ($width) $width = "-w $width";
}

// generate the temporary file
if (!file_put_contents(SAVE_PATH."$tempName.svg", $svg)) {
die("Couldn't create temporary file. Check that the directory permissions for
the /temp directory are set to 777.");
}

if(IS_WIN){
$output = shell_exec("java -jar ". BATIK_PATH ." $typeString -d $outfile $width ".SAVE_PATH."$tempName.svg");
}else{
$output = shell_exec("/usr/local/jdk1.8.0_66/bin/java -jar ". BATIK_PATH ." $typeString -d $outfile $width ".SAVE_PATH."$tempName.svg");
}


// catch error
if (!is_file($outfile)) {
echo "<pre>$output</pre>";
echo "Error while converting SVG. ";

}
else {
return $outfile;
}

} else if ($ext == 'svg') {
header("Content-Disposition: attachment; filename=\"$filename.$ext\"");
header("Content-Type: $type");
echo $svg;

} else {
echo "Invalid type";
}
}

文件保存到本地,然后就可以随便搞了。
你要是实在嫌安装JAVA环境麻烦,可以直接模拟提交请求官方的导出地址。然后会返回一个图片名称,你可以下载下来,服务器会保存30个小时,具体可以参考
[url]http://www.highcharts.com/docs/export-module/export-module-overview[/url]
[url]http://jsfiddle.net/6h8o16g0/[/url]
你只要按他的格式传递给他SVG参数就可以了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值