VB.Net Tutorial on Webpage Screen capture
When we need to take a screen shot of the web page(entire page), this class will be helpful. This class converts any web page written in any programming language if it renders in browser. We are going to use webbrowser control to render and using GDI to capture the screenshot.
The title given to this article, may mislead some how technically. But it is given for understanding purposes. Actually this class navigates to the given url using the .Net 2.0's Web Browser control. Once the navigation completed, the screen shot image can be taken with the help of GDI, and is instantaneous - don't worry about downloading images as the file is already on the offline portion of your computer, so whether or not you have unlimited hosting capabilities through broadband or a 56k connection doesn't matter.
Again taking the screenshot of the given webpage is much easier using the built in function DrawToBitmap of Web Browser component which yields a bitmap image. This image can be either saved in the hard disk or can be forced into the response stream for displaying in another webpage.
Source Code for the Tutorial
Imports Microsoft.VisualBasic
Imports System.Threading
Imports System.Drawing
Imports System.Windows.Forms
Public Class ImageFromHtml
Private PageUrl As String
Private ConvertedImage As Bitmap
Private m_intHeight As Integer
Public Property Height() As Integer
Get
Return m_intHeight
End Get
Set(ByVal value As Integer)
m_intHeight = value
End Set
End Property
Private m_intWidth As Integer
Public Property Width() As Integer
Get
Return m_intWidth
End Get
Set(ByVal value As Integer)
m_intWidth = value
End Set
End Property
Public Function ConvertPage(ByVal PageUrl As String) As Bitmap
Me.PageUrl = PageUrl
Dim thrCurrent As New Thread(New ThreadStart(AddressOf CreateImage))
thrCurrent.SetApartmentState(ApartmentState.STA)
thrCurrent.Start()
thrCurrent.Join()
Return ConvertedImage
End Function
Private Sub CreateImage()
Dim BrowsePage As New WebBrowser()
BrowsePage.ScrollBarsEnabled = False
BrowsePage.Navigate(PageUrl)
AddHandler BrowsePage.DocumentCompleted, AddressOf _
WebBrowser_DocumentCompleted
While BrowsePage.ReadyState <> WebBrowserReadyState.Complete
Application.DoEvents()
End While
BrowsePage.Dispose()
End Sub
Private Sub WebBrowser_DocumentCompleted(ByVal sender As Object, ByVal e As _
WebBrowserDocumentCompletedEventArgs)
Dim BrowsePage As WebBrowser = DirectCast(sender, WebBrowser)
BrowsePage.ClientSize = New Size(Width, Height)
BrowsePage.ScrollBarsEnabled = False
ConvertedImage = New Bitmap(Width, Height)
BrowsePage.BringToFront()
BrowsePage.DrawToBitmap(ConvertedImage, BrowsePage.Bounds)
End Sub
End Class