我希望能够阅读网站的屏幕截图,并尝试使用phantomjs和ASP.NET。
我尝试过使用page.render将屏幕截图保存到文件中。它作为控制台应用程序,但不是我从asp.net处理程序调用它。这可能是由于文件权限,因为简单的应用程序(如hello.js)工作正常。
没关系,我的偏好不是写入文件,而是处理字节并直接从处理程序返回图像。
我对如何做到这一点有点失落。我注意到一个名为page.renderBase64的方法,但不知道如何使用它。
目前我正在使用IHttpHandler。
这里有一个类似的问题,但那个人最终放弃了phantomjs。我喜欢它的外观,并希望尽可能继续使用它。 Running Phantomjs using C# to grab snapshot of webpage
答案 0 :(得分:10)
根据您的上一条评论,您可以在phantom js文件中执行以下操作:
var base64image = page.renderBase64('PNG');
system.stdout.write(base64image);
在C#中:
var startInfo = new ProcessStartInfo {
//some other parameters here
...
FileName = pathToExe,
Arguments = String.Format("{0}",someParameters),
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
WorkingDirectory = pdfToolPath
};
var p = new Process();
p.StartInfo = startInfo;
p.Start();
p.WaitForExit(timeToExit);
//Read the Error:
string error = p.StandardError.ReadToEnd();
//Read the Output:
string output = p.StandardOutput.ReadToEnd();
在输出变量中,您可以读取从phantomJS返回的base64,然后执行您计划使用的内容。
答案 1 :(得分:3)
你可以在这里获得rastor的js:rastorize
然后C#中的以下代码就可以完成这项工作。
var phantomJS=new PhantomJS();
phantomJS.Run("rasterize.js", new[] { "http://google.com","ss.pdf" });
答案 2 :(得分:2)
这个问题源于我对base64字符串实际上缺乏了解。
在运行phantomjs的javascript文件中,我可以将base64图像直接写入控制台,如下所示:
var base64image = page.renderBase64('PNG');
console.log(base64image);
在运行phantomjs的c#代码中,我可以将控制台输出转换回字节并将图像写入响应,如下所示:
var info = new ProcessStartInfo(path, string.Join(" ", args));
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.CreateNoWindow = true;
var p = Process.Start(info);
p.Start();
var base64image = p.StandardOutput.ReadToEnd();
var bytes = Convert.FromBase64CharArray(base64image.ToCharArray(), 0, base64image.Length);
p.WaitForExit();
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
context.Response.ContentType = "image/PNG";
这似乎避免了我遇到的文件锁定问题。
答案 3 :(得分:1)
使用CasperJS和PhantomJS,我一直在拍摄漂亮的网页照片。
var casper = require('casper').create();
casper.start('http://target.aspx', function() {
this.capture('snapshot.png');
});
casper.run(function() {
this.echo('finished');
});
我强烈建议您查看该工具。我仍然不确定如何做回发后..
答案 4 :(得分:0)
设置ProcessStartInfo对象的“WorkingDirectory”属性,以指定文件的保存位置。