Generate Screenshot From WebBrowser Control
I grabbed some code from the link below to generate a screenshot from a web browser control: http://pietschsoft.com/post/2008/07/C-Generate-WebPage-Thumbmail-Screenshot-Image.aspx
Then, I modified to be an extension method like so:
public static Bitmap GetScreenshot(this WebBrowser webBrowser)
{
// Load the webpage into a WebBrowser control
using (WebBrowser wb = new WebBrowser())
{
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(webBrowser.Url);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
// Set the size of the WebBrowser control
wb.Width = wb.Document.Body.ScrollRectangle.Width;
wb.Height = wb.Document.Body.ScrollRectangle.Height;
// Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
开发者_StackOverflow Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
return bitmap;
}
}
It works great for most web pages, but I am trying to use it for a SharePoint site and the image is coming out as 250x250 every time. :-s
Any geniuses here that can give me a solution?
Thanks in advance
Well, the reason for this seems to be that my new WebBrowser (wb) is uninitialized even after I call Navigate(). The Url property shows as null. This is weird. Does it mean I cannot create a WebBrowser in code and never display it? It would be a shame to have to display the thing. :-(
You can check that question taking-screenshot-of-a-webpage-programmatically.
It is based on this webpage_thumbnailer which uses Web Browser control.
For one, the DrawToBitmap class does not exist under the webbrowser control. I suggest using CopyFromScreen. Here is a code snippet:
Bitmap b = new Bitmap(wb.ClientSize.Width, webBrowser1.ClientSize.Height);
Graphics g = Graphics.FromImage(b);
g.CopyFromScreen(this.PointToScreen(wb.Location), new Point(0, 0), wb.ClientSize);
//The bitmap is ready. Do whatever you please with it!
b.Save(@"c:\screenshot.jpg", ImageFormat.Jpeg);
MessageBox.Show("Screen Shot Saved!");
精彩评论