使用highcharts 实现本地服务器导出图片

一。Higcharts  中文网

      HighChart中文网, 非常好的中文网站 , 并有精简的demo  http://www.hcharts.cn/   强烈推荐

      http://www.hcharts.cn/

二。 highcharts 图片导出功能( 下载图片):

     2.1  从highcharts 远程官网服务器实现图片下载

       参考代码 : highcharst 中文网

       http://www.hcharts.cn/demo/index.php?p=88

     2.2  从本地服务器实现图片下载 (php 实现  与  ruby on rails 实现)

      highcharts  生成的chart 格式是svg, 我们要下载的图片是jpg的, 实现中间的转换需要插件 batik 

      下载官网: http://xmlgraphics.apache.org/batik/    该插件是是基于java的 图片格式转换工具

      在2.1的下载页面下载svg 格式的图片(可以使用浏览器打开)

      1. 命令行转换:

                java -jar batik-rasterizer.jar -m image/png test.svg     // 吧 test.svg  转化为 test.png格式

     2.   php  实现的 本地下载服务 

          highcharts 压缩包的 exporting-server/php/php-batik/index.php

<?php
/**
 * This file is part of the exporting module for Highcharts JS.
 * www.highcharts.com/license
 * 
 *  
 * Available POST variables:
 *
 * $filename  string   The desired filename without extension
 * $type      string   The MIME type for export. 
 * $width     int      The pixel width of the exported raster image. The height is calculated.
 * $svg       string   The SVG source code to convert.
 */


// Options
define ('BATIK_PATH', 'batik-rasterizer.jar');

///
ini_set('magic_quotes_gpc', 'off');

$type = $_POST['type'];
$svg = (string) $_POST['svg'];
$filename = (string) $_POST['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 topped, 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 = "temp/$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("temp/$tempName.svg", $svg)) { 
		die("Couldn't create temporary file. Check that the directory permissions for
			the /temp directory are set to 777.");
	}
	
	// do the conversion     执行shell 进行转换 输出到指定文件
	$output = shell_exec("java -jar ". BATIK_PATH ." $typeString -d $outfile $width temp/$tempName.svg");
	
	// catch error
	if (!is_file($outfile) || filesize($outfile) < 10) {
		echo "<pre>$output</pre>";
		echo "Error while converting SVG. ";
		
		if (strpos($output, 'SVGConverter.error.while.rasterizing.file') !== false) {
			echo "
			<h4>Debug steps</h4>
			<ol>
			<li>Copy the SVG:<br/><textarea rows=5>" . htmlentities(str_replace('>', ">\n", $svg)) . "</textarea></li>
			<li>Go to <a href='http://validator.w3.org/#validate_by_input' target='_blank'>validator.w3.org/#validate_by_input</a></li>
			<li>Paste the SVG</li>
			<li>Click More Options and select SVG 1.1 for Use Doctype</li>
			<li>Click the Check button</li>
			</ol>";
		}
	} 
	
	// stream it
	else {       //  下载图片的服务
		header("Content-Disposition: attachment; filename=\"$filename.$ext\"");
		header("Content-Type: $type");
		echo file_get_contents($outfile);
	}
	
	// delete it
	unlink("temp/$tempName.svg");
	unlink($outfile);

// SVG can be streamed directly back
} else if ($ext == 'svg') {
	header("Content-Disposition: attachment; filename=\"$filename.$ext\"");
	header("Content-Type: $type");
	echo $svg;
	
} else {
	echo "Invalid type";
}
?>

   3.  使用ruby自己实现的本地下载

      前端  haml  页面代码  

      %br
      %p{style: 'margin-left:20px'}
      %button#downloadChart  导出统计图片      // 页面按钮
      %button#downloadWord   下载报告模板
%script{:src => "/highcharts.js", :type => "text/javascript"}
%script{:src => "/exporting.js", :type => "text/javascript"}
:javascript
  $(document).ready(function () {
    var chart = new Highcharts.Chart({     // chart 对象
      chart: {
        type: 'column',
        renderTo: 'target'
      },
      title: {
        text: '<b>目标值</b>'
      },
      subtitle: {
        text: ''
      },
      exporting: {
        filename: "target",
        type: "image/png",
        //url:'http://127.0.0.1:4567/'
        width:1000
      },
      xAxis: {
        categories: [
        "#{_processareas.map{|processarea| processarea.upcase}.join '","'}"
        ]
      },
      yAxis: {
        min: 0,
        max: 10,
        tickInterval: 2,
        title: {
          text: '<b>分  值</b>'
        }
      },
      tooltip: {
        headerFormat: '<span style="font-size:14px; margin: 0 0 6px 0">{point.key}</span><table>',
        pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
          '<td style="padding:0"><b>{point.y:.1f}</b></td></tr>',
        footerFormat: '</table>',
        shared: true,
        useHTML: true
      },
      plotOptions: {
        column: {
          pointPadding: 0.2,
          borderWidth: 0,
          pointWidth: 20,
          groupPadding: 0.15
        }
      },
      series: [#{
        _marks.map{|group, points|
          "{name: '#{group.upcase}', data: [#{points.join(', ')}]}" 
        }.join(', ')
      }, {
        name: 'PA',
        data: [#{_processarea_marks.join(',')}]
      }]
    });	
	
    $('#downloadChart').click(function(){    // 导出图片button
          var data = chart.getSVG();
          //alert(data);
          //window.open("/img?_data="+data);
          var tmp = document.createElement("Form"); // 图片内容大,使用post, 通过javascript使用post
          tmp.action = "/img";
          tmp.method = "post";
          var pagam = document.createElement("textarea");   // <testarea > </textarea>
          pagam.name = "_data";
          pagam.value = data;
          tmp.appendChild(pagam);
          document.body.appendChild(tmp);
          tmp.submit();                          // 即js 创建表单的过程
    });
    $("#downloadWord").click(function(){    // 导出文档按钮

         //var word = "等级"+"#{_level}"+"模板.doc";
         //alert(window.location.pathname);
         window.location.href ="/doc?level=#{_level}";   //js代开后台服务的连接
		 
    });
  });

  服务器:  ruby 服务代码

   batik 需要java jdk , 所以要把jdk的相关文件拷贝的本地服务器的相关文件夹, 也可以通过bat文件中设置path 添加

  bat: 

set PATH=%PATH%;%CD%\bin
post  '/img' do
  
  data = params[:_data]
  oFile = File.new("target.svg", "r+")
  oFile.syswrite("#{data}")
                        #  使用反斜杠执行shell,exec 执行后,后面的代码不执行, 所以不用
  our = ` java -jar batik-rasterizer.jar -m image/png -d ss.png  target.svg `  // ss.png 是中间文件
      #  our 是shell执行的结果
  iFile = File.new("ss.png", "rb")
  len = File.size?(iFile) 
  content = iFile.sysread(len.to_i)    // ruby 读入图片文件(rb)代码
  
  headers({'Content-Type' => 'image/png',        // header 下载图片
    'Content-Disposition' => "attachment;filename=\"target.png\""})   
  return content     // 写入图片内容
end



#export to doc  _level:
get '/doc' do
 
   #  to-do  
   
  headers({'Content-Type' => 'text/plain',
    'Content-Description' => 'File Transfer',
    'Content-Transfer-Encoding' => 'utf-8',
    'Content-Disposition' => "attachment;filename=\"#{filename}.doc\"",
    'Expires' => '0',
    'Pragma' => 'public'})   //下载文档的 服务
  return content	
end


三 。下载文档:

       见上面代码

转载于:https://my.oschina.net/badboy2/blog/380135

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值