Running Phantomjs using C# to grab snapshot of web

2019-01-21 17:22发布

问题:

I'm trying to grab snapshots of my own website using phantomjs - basically, this is to create a "preview image" of user-submitted content.

I've installed phantomjs on the server and have confirmed that running it from the command line against the appropriate pages works fine. However, when I try running it from the website, it does not appear to do anything. I have confirmed that the code is being called, that phantom is actually running (I've monitored the processes, and can see it appear in the process list when I call it) - however, no image is being generated.

I'm not sure where I should be looking to figure out why it won't create the images - any suggestions? The relevant code block is below:

string arguments = "/c rasterize.js http://www.mysite.com/viewcontent.aspx?id=123";
string imagefilename = @"C:\inetpub\vhosts\mysite.com\httpdocs\Uploads\img123.png";

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = false;
p.StartInfo.FileName = @"C:\phantomjs.exe";
p.StartInfo.Arguments = arguments + " " + imagefilename;

p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

回答1:

I check the errors that phantomjs throws during its process. You can read them from Process.StandardError.

var startInfo = new ProcessStartInfo();
//some other parameters here
...
startInfo.RedirectStandardError = true;
var p = new Process();
p.StartInfo = startInfo;
p.Start();
p.WaitForExit(timeToExit);
//Read the Error:
string error = p.StandardError.ReadToEnd();

It will give you an idea of what happened



回答2:

The easiest way for executing phantomjs from C# code is using wrapper like NReco.PhantomJS. The following example illustrates how to use it for rasterize.js:

var phantomJS = new PhantomJS();
phantomJS.Run( "rasterize.js", new[] { "https://www.google.com", outFile} );

Wrapper API has events for stdout and stderr; also it can provide input from C# Stream and read stdout result into C# stream.