c#中使用Cefsharp的完整页面截图

本文关键字:Cefsharp | 更新日期: 2023-09-27 18:06:17

我已经下载了Minimalexample.Offscreen的例子。这是我使用的代码截图,但我没有得到完整的页面。图像被裁剪(只截取可见的页面截图)。

//   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();

我怎么能得到完整的长页截图与CefSharp屏幕外或CefSharp winforms?

c#中使用Cefsharp的完整页面截图

经过很长一段时间,我找到了解决办法。重点是根据页面高度设置webview的高度,然后截图。

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");

可能是因为您只等待了半秒钟页面加载。看看在谷歌浏览器上加载需要多少时间,并给这几秒钟。用三秒钟的时间加上

Thread.Sleep(3000);