Full page screenshot with Cefsharp in C#

skhurams picture skhurams · Sep 9, 2016 · Viewed 7.3k times · Source

I have downloaded example of Minimalexample.Offscreen. This is the code I'm using for screenshot but I'm not getting the full page. The image is cropped (only visible page screenshot is taken).

//   c# code
 var scriptTask = browser.EvaluateScriptAsync("document.getElementById('lst-ib').value = 'CefSharp Was Here!'");
        scriptTask.ContinueWith(t =>
                {
                    Thread.Sleep(500);
                    var task = browser.ScreenshotAsync();
                    task.ContinueWith(x =>
                    {
                        var screenshotPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharp screenshot.png");

                        Console.WriteLine();
                        Console.WriteLine("Screenshot ready. Saving to {0}", screenshotPath);
                        task.Result.Save(screenshotPath);
                        task.Result.Dispose();
                        Console.WriteLine("Screenshot saved.  Launching your default image viewer...");                       
                        Process.Start(screenshotPath);
                        Console.WriteLine("Image viewer launched.  Press any key to exit.");            
                    }, TaskScheduler.Default);
                  }).Wait();

How can I get the full long page screenshot with CefSharp offscreen or Cefsharp winforms?

Answer

skhurams picture skhurams · Jan 14, 2021

After long period of time i found the solution. The main point is to set webview height according to page height and then take screenshot.

CefSharp.OffScreen.ChromiumWebBrowser WebView =new CefSharp.OffScreen.ChromiumWebBrowser(siteUrl);
            
            int width = 1280;
            int height = 1480;

            string jsString = "Math.max(document.body.scrollHeight, " +
                              "document.documentElement.scrollHeight, document.body.offsetHeight, " +
                              "document.documentElement.offsetHeight, document.body.clientHeight, " +
                              "document.documentElement.clientHeight);";


            var executedScript = WebView.EvaluateScriptAsync(jsString).Result.Result;

            height = Convert.ToInt32(executedScript);

            var size = new Size(width, height);

            WebView.Size = size;

            Thread.Sleep(500);
            // Wait for the screenshot to be taken.
            var bitmap = WebView.ScreenshotOrNull();
            bitmap.Save(@"Test.jpg");