C# Save Web Page URL To Image
Posted by in CSharp December 2, 2011 1 Comment

Simple C# code below will capture a particular web page via its URL and save it to an image. It can work with long scrolling web page that includes images, JavaScript and even with Flash. That means a fully web page will be captured and saved to an image file.

Note that we will get a large image if the web page we’re capturing is too long (small scroll bar) and the generated image is very similar with what we see when explore this web page in Internet Explorer

I know that there are some tools and services that allow you to do that but if you’re working on .Net form application, the C# code below may become your own solution.

C# Save Web Page To Image

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            string url = "http://4rapiddev.com/facebook-graph-api/php-load-facebook-albums-and-save-to-mysql-database/";
 
            Bitmap thumbnail = SaveWebPage2Image(url);
 
            //specify where image will be save
            thumbnail.Save("d:/web-shot.png", System.Drawing.Imaging.ImageFormat.Png);
        }
 
        public Bitmap SaveWebPage2Image(string url)
        {
            // Load the webpage into a WebBrowser control
            WebBrowser wb = new WebBrowser();
            wb.ScrollBarsEnabled = false;
            wb.ScriptErrorsSuppressed = true;
            wb.Navigate(url);
 
            while (wb.ReadyState != WebBrowserReadyState.Complete) { System.Windows.Forms.Application.DoEvents(); }
 
            // Take Screenshot of the web pages full width
            wb.Width = wb.Document.Body.ScrollRectangle.Width;
 
            // Take Screenshot of the web pages full height
            wb.Height = wb.Document.Body.ScrollRectangle.Height;
 
            // Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
            Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
            wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
            wb.Dispose();
 
            return bitmap;
        }
    }
}

Example:

web-shot

web-shot

Few notes here:

  • 1. Using System.Drawing namespace
  • 2. Replace URL with URL of web page you want to save
  • 3. Specify where you want to save the image

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • kayal

    Thank you… worked like charm