C#中使用Cefsharp进行全页面截图

3

我已经下载了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 offscreen或CefSharp WinForms获取完整的长页面截图?

为什么不使用 async/await?没有支持 Task 但不支持 async/await 的 .NET 版本(提示)。这将使您的代码更清晰,并避免因未执行 Dispose 调用而导致泄漏。正如 此讨论所示,您的页面可能没有完全加载,因此 ScreenshotAsync 只捕获了第一帧。 - Panagiotis Kanavos
你能给一个演示代码示例吗?现在没有任何示例,并且也没有其他的截图函数,只有screenshotasync是可用的。 - skhurams
现在我已经更新了代码并添加了等待,但问题仍然存在。 - skhurams
//我也运行了这段代码 var bitmap = browser.ScreenshotOrNull();bitmap.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "ScreenPage.png")); //但仍然收到裁剪后的图像 - skhurams
2个回答

3

经过长时间的探索,我找到了解决方法。关键在于根据页面高度设置 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");

2
也许是因为您只等待页面加载了半秒钟。请在Google Chrome上查看加载时间,并添加相应的等待时间。如果需要三秒钟,请添加以下代码:

Thread.Sleep(3000);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接