.net core 利用Selenium和PhantomJS后台生成EChart图片

1.引用

NuGet安装:

Selenium.Support

Selenium.WebDriver

Selenium.WebDriver.PhantomJS.CrossPlatform  (分布Linux时把对应PhantomJS复制到发布目录)

2.后台打开的页面

 

@{
    Layout = "/Views/Shared/Ordinary.cshtml";
    ViewData["Title"] = "图表模版";
}
@section css{
    "@ViewBag.url/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
}
"chartmain" class="col-lg-12 col-sm-12" style="height:400px;width:600px;">
View Code

 

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());//打开链接
View Code
//执行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();
View Code

 

错误: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

你可能感兴趣的:(.net core 利用Selenium和PhantomJS后台生成EChart图片)