Capture a complete website in C#

To take a screenshot is one thing. One click on the print key or a small program, which uses the c# screenshot capture method, I showed you the last time, are enough to take a beautiful screenshot.
But what should you do, if you want to capture a whole website? The most websites are “longer” as your screen is high. Thereby most common ways to capture a screenshot will become useless.

But don’t fear – C# can of course solve this problem. If you want to capture a screenshot of a complete website, take a look at the following snippet.

 private void WebsiteScreenshot(string url, string file)
 {
     //Create a webbrwoser object
     WebBrowser browser = new WebBrowser();

     //Deactivate scrollbars, unless you want them to
     //appear on your screenshot
     browser.ScrollBarsEnabled = false;

     //Suppress (java-)script error popups
     browser.ScriptErrorsSuppressed = true;

     //Open the given url in webbrowser
     browser.Navigate(new Uri(url));

     //Wait until the page is fully loaded
     while (browser.Document == null || browser.Document.Body == null)
            Application.DoEvents();

      //Resize the webbrowser object to the same size as the
      //webpage
      Rectangle websiteSize = browser.Document.Body.ScrollRectangle;
      browser.Size = new Size(websiteSize.Width,websiteSize.Height);

      //Create a bitmap object with the same dimensions as the website
      Bitmap bmp = new Bitmap(websiteSize.Width, websiteSize.Height);

      //Paint the website contents to the bitmap
      browser.DrawToBitmap(bmp,
           new Rectangle(0, 0, websiteSize.Width, websiteSize.Height));

      browser.Dispose();

      //Save the bitmap at the given filepath
      bmp.Save(file, ImageFormat.Png);
 }

You can then call the method as follows:

   //If you want file extension than .png, don't forget to change the
   //ImageFormat-type in the above main function!
   WebsiteScreenshot("http://en.code-bude.net/", "c:\website_screenshot.png");

As always, if you have questions, write me a comment!

2 Comments

  1. Ricksays:

    Hi,

    Great post, I have done something similar… but am facing some challenges with websites that are responsive using max-width.
    Those websites are causing the width and height to be incorrect.
    Have you experience anything similar and have any solutions for?

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked