Search code examples
.netawesomium

How to retrieve the whole page screenshot be awesomium?


The problem is that width and height are set during WebView creation and I don't see any option to change it after page was loaded (and real size became known). To workaround it I use two WebView: first to get the size and second to make a screenshot:

static bool finishedLoading;
static bool finishedScroll;
static ScrollData scrollData;

static void Main(string[] args)
{
   WebCore.Initialize(new WebCoreConfig() { CustomCSS = "::-webkit-scrollbar { visibility: hidden; }" });

   var webView1 = WebCore.CreateWebView(800, 600, false);
   webView1.LoadURL("http://someurl");
   webView1.LoadCompleted += OnFinishLoading;

   while (!finishedLoading)
   {
      Thread.Sleep(100);
      WebCore.Update();
   }

   webView1.RequestScrollData();
   webView1.ScrollDataReceived += new ScrollDataReceivedEventHandler(ScrollDataReceived);

   while (!finishedScroll)
   {
      Thread.Sleep(100);
      WebCore.Update();
   }

   var webView2 = WebCore.CreateWebView(scrollData.ContentWidth, scrollData.ContentHeight, false);

   finishedLoading = false;
   webView2.LoadURL("http://someUrl");
   webView2.LoadCompleted += OnFinishLoading;

   while (!finishedLoading)
   {
      Thread.Sleep(100);
      WebCore.Update();
   }

   webView2.Render().SaveToPNG("filePath");

   WebCore.Shutdown();
}

static void ScrollDataReceived(object sender, ScrollDataEventArgs e)
{
   finishedScroll = true;
   scrollData = e.ScrollData;
}

static void OnFinishLoading(object sender, EventArgs e)
{
   finishedLoading = true;
}

I hope there is a better way...


Solution

  • Instead of creating a new WebView after you receive the scroll dimensions, you just need to resize it using WebView.Resize and then wait for the resize operation to complete (see WebView.IsResizing).

    I recently wrote a tutorial on how to capture whole web-pages using Awesomium: http://labs.awesomium.com/capturing-web-pages-with-c/

    The code uses the C API but it should be very similar to the .NET API. There's also a complete code example (link is near the bottom) that demonstrates how to capture very long web-pages to multiple images without killing your RAM.

    Hope this helps!