A graph is being generated in a webpage. I am trying to do a screen capture with C# code. I tried the code below. It worked a few times and now I get "index was out of range. must be non-negative and less than the size of the collection" error.
Any help or guidance is appreciated. Thanks in advance.
System.Drawing.Bitmap bitMap = null;
static AutoResetEvent autoEvent;
public void DownloadAsImage(string title, string location)
{
autoEvent = new AutoResetEvent(false);
Uri url = HttpContext.Current.Request.Url;
string RootUrl = url.AbsoluteUri.Replace(url.PathAndQuery, string.Empty);
//ApartmentState:specifies the state of a system.threading.thread
//STA:Thread will create and enter a single-threaded apartment
Thread t = new Thread(CaptureWebPageToDisplay);
t.SetApartmentState(ApartmentState.STA);
if (title == "PieGraph" && location == "0")
{
t.Start(RootUrl + "/_Layouts/AppPage/Reports/TotalGraphPage.aspx?isdlg=1");
Thread.Sleep(30000);
}
else
{
t.Start(RootUrl + "/_Layouts/AppPage/Reports/GraphPage.aspx?isdlg=1&Title=" + title + "&Location=" + location);
Thread.Sleep(10000);
}
autoEvent.Set();
HttpContext.Current.Response.ContentType = "image/jpeg";
string targetFolder = Server.MapPath(@".\GraphImages\") + title + ".Jpeg";
try
{
bitMap.Save(targetFolder);
bitMap.Dispose();
}
catch(Exception ex){
DBLogger.ExpandException(ex);
if (bitMap != null)
{
bitMap.Dispose();
}
}
}
public void CaptureWebPageToDisplay(object URL)
{
// create a hidden web browser, which will navigate to the page
System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
// Full web browser
web.Dock = System.Windows.Forms.DockStyle.Fill;
web.Size = new System.Drawing.Size(1000, 800);
// we don't want scrollbars on our image
web.ScrollBarsEnabled = false;
// don't let any errors shine through
web.ScriptErrorsSuppressed = true;
// let's load up that page!
web.Navigate((string)URL);
// wait until the page is fully loaded
while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(5000); // allow time for page scripts to update
// the appearance of the page
// set the size of our web browser to be the same size as the page
int width = web.Document.Body.ScrollRectangle.Width;
int height = web.Document.Body.ScrollRectangle.Height;
web.Width = width;
web.Height = height;
// a bitmap that we will draw to
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height);
// change background color to white, just in case
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
g.Clear(System.Drawing.Color.White);
// create rectangle.
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(20, 0, width, height);
// draw the web browser to the bitmap
web.DrawToBitmap(bmp, rect);
bitMap = bmp;
}