1.引用
NuGet安装:
Selenium.Support
Selenium.WebDriver
Selenium.WebDriver.PhantomJS.CrossPlatform (分布Linux时把对应PhantomJS复制到发布目录)
2.后台打开的页面
@{ Layout = "/Views/Shared/Ordinary.cshtml"; ViewData["Title"] = "图表模版"; } @section css{ <link href="@ViewBag.url/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" /> } <div id="chartmain" class="col-lg-12 col-sm-12" style="height:400px;600px;"></div> <script src="@ViewBag.url/lib/jquery/dist/jquery.js"></script> <script src="@ViewBag.url/js/echarts.min.js"></script> <script type="text/javascript"> var time = []; var nameArr = [ ]; //指定图标的配置和数据 var option = { title: { text: 'chart' }, tooltip: { trigger: 'axis', axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985' } } }, toolbox: {//平铺、折叠、生成png图片 show: true, feature: { dataView: { readOnly: false }, magicType: { show: true, type: ['stack', 'tiled', 'line', 'bar'] }, restore: { show: true }, saveAsImage: { show: true } } }, xAxis: { type: 'category', boundaryGap: false, splitLine: { show: true,//是否显示网格线 }, name: "time" }, yAxis: { type: 'value', axisLabel: { formatter: '{value}' }, name: "value", splitLine: { show: true,//是否显示网格线 } }, series: [{ name: 'value', type: 'line', data: nameArr }] }; //初始化echarts实例 var myChart = echarts.init(document.getElementById('chartmain')); //使用制定的配置项和数据显示图表 myChart.setOption(option); function getTime(date) { var Hours = date.getHours();//获取当前小时数(0-23) var Minutes = date.getMinutes(); //获取当前分钟数(0-59) var Seconds = date.getSeconds();//获取当前秒数(0-59) var Milliseconds = date.getMilliseconds();//获取当前毫秒数(0-999) return Hours + ":" + Minutes + ":" + Seconds } </script>
3.生成图片代码
PhantomJSDriverService pds = PhantomJSDriverService.CreateDefaultService(AppDomain.CurrentDomain.BaseDirectory.ToString()); var driver = new PhantomJSDriver(pds); var request = injection.GetHttpContext.HttpContext.Request; StringBuilder url = new StringBuilder(); url.Append(request.Scheme); url.Append("://"); url.Append(request.Host); url.Append("/Business/Report/TemplateEChart"); driver.Navigate().GoToUrl(url.ToString());//打开链接
//执行js ((IJavaScriptExecutor)driver).ExecuteScript("myChart.setOption(" + JsonHelper.ObjectToJson(ff) + ");"); //截图保存 Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot(); string mapPath = @hostingEnvironment.WebRootPath; string imgPatht = "/report/tempImg"; string dirt = mapPath + imgPatht; if (!Directory.Exists(dirt)) { DirectoryInfo dirInfo = Directory.CreateDirectory(dirt); } string imgSrct = imgPatht + "/" + Guid.NewGuid().ToString() + ".png"; string fullPatht = mapPath + imgSrct; screenshot.SaveAsFile(fullPatht, ScreenshotImageFormat.Png); //退出 driver.Quit();
错误:Permission denied
解决方法:PhantomJS文件设置最高权限
错误:System.TypeInitializationException: The type initializer for 'Gdip' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'libgdiplus': The specified module could not be found.
解决方法:Linux安装 yum install libgdiplus