Capture Screenshot Image of Website in ASP.Net.

Description:-

In this article I will explain how to capture a screenshot (snapshot) of a Website web page using ASP.Net using C#.  the WebBrowser is a Windows Forms controls, in order to use it in ASP.Net Web Projects, we will have to add reference to the following libraries.

When the Button is clicked the following event handler is raised, here a new Thread is initiated and the WebBrowser control is initialized within the Thread. For the WebBrowser I have attached aDocumentCompleted event handler which will be raised when the Web Page is loaded inside the browser.

Note: Since ASP.Net applications work in Multi-Threaded Apartments (MTA) we need to start a new Thread for the WebBrowser control and execute the Thread in Single-Threaded Apartments (STA).

Inside the DocumentCompleted event handler, the Web Page loaded inside the WebBrowser control is drawn to a Bitmap which is then converted to a Byte Array and then to Base64 string so that it can be displayed in the Image control.

Default.aspx:-
<div>
  <asp:TextBox ID="txtUrl" runat="server" Text="" />
  <asp:Button ID="Button1" Text="Capture" runat="server" OnClick="Capture" />
  <br />
  <asp:Image ID="imgScreenShot" runat="server" Height="300" Width="400" Visible="false" />
</div>

Default.aspx.cs:-
protected void Capture(object sender, EventArgs e)
{
    string url = txtUrl.Text.Trim();
    Thread thread = new Thread(delegate()
    {
        using (WebBrowser browser = new WebBrowser())
        {
            browser.ScrollBarsEnabled = false;
            browser.AllowNavigation = true;
            browser.Navigate(url);
            browser.Width = 1024;
            browser.Height = 768;
            browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentCompleted);
            while (browser.ReadyState != WebBrowserReadyState.Complete)
            {
                System.Windows.Forms.Application.DoEvents();
            }
        }
    });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();
}

private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    WebBrowser browser = sender as WebBrowser;
    using (Bitmap bitmap = new Bitmap(browser.Width, browser.Height))
    {
        browser.DrawToBitmap(bitmap, new Rectangle(0, 0, browser.Width, browser.Height));
        using (MemoryStream stream = new MemoryStream())
        {
            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] bytes = stream.ToArray();
            imgScreenShot.Visible = true;
            imgScreenShot.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
        }
    }
}

Related Posts

Previous
Next Post »

Thanks for comments.....