首頁  >  文章  >  後端開發  >  php+batik 實現匯出highchart圖片功能

php+batik 實現匯出highchart圖片功能

巴扎黑
巴扎黑原創
2016-11-09 14:21:201393瀏覽

最近有個匯出需求需要將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 == &#39;image/png&#39;) {
$typeString = &#39;-m image/png&#39;;
$ext = &#39;png&#39;;
} elseif ($type == &#39;image/jpeg&#39;) {
$typeString = &#39;-m image/jpeg&#39;;
$ext = &#39;jpg&#39;;
} elseif ($type == &#39;application/pdf&#39;) {
$typeString = &#39;-m application/pdf&#39;;
$ext = &#39;pdf&#39;;
} elseif ($type == &#39;image/svg+xml&#39;) {
$ext = &#39;svg&#39;;
} else { // prevent fallthrough from global variables
$ext = &#39;txt&#39;;
}
$outfile = SAVE_PATH.$tempName.&#39;.&#39;.$ext;
if (isset($typeString)) {
// size
$width = &#39;&#39;;
if ($_POST[&#39;width&#39;]) {
$width = (int)$_POST[&#39;width&#39;];
if ($width) $width = "-w $width";
}
// generate the temporary file
if (!file_put_contents(SAVE_PATH."$tempName.svg", $svg)) {
die("Couldn&#39;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 class="brush:php;toolbar:false">$output
"; 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環境麻煩,可以直接模擬提交請求官方的匯出位址。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn