隐藏

在C#开发中CefSharp截取完整网页图片,网页截图

发布:2023/9/17 11:53:11作者:管理员 来源:本站 浏览次数:884

开发语言C#

框架集.net framework 4.6

需要安装nuget包CefSharp.OffScreen


参考使用CefSharp.OffScreen框架地址

https://github.com/cefsharp/CefSharp/blob/master/CefSharp.OffScreen.Example/Program.cs


将一个网页完整的页面通过代码生成图片


using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

using CefSharp;

using CefSharp.DevTools.Page;

using CefSharp.OffScreen;


namespace ConsoleApp_HtmlScreenshot

{

   internal class Program

   {


       static async Task Main(string[] args)

       {

#if ANYCPU

           //Only required for PlatformTarget of AnyCPU

           CefRuntime.SubscribeAnyCpuAssemblyResolver();

#endif

           //要截取图片的网页URL

           const string testUrl = "https://list.jd.com/list.html?cat=670,671,1105";


           var settings = new CefSettings()

           {

               //By default CefSharp will use an in-memory cache, you need to specify a Cache Folder to persist data

               //CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache")

           };


           //Perform dependency check to make sure all relevant resources are in our output directory.

           Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);


           // Create the offscreen Chromium browser.

           var browser = new ChromiumWebBrowser(testUrl);

           //browser.Size = new System.Drawing.Size(1920, 20000);


           //browser.FrameLoadEnd += (s, e) =>{

           //    Console.WriteLine("1加载完成 "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

           //};


           //等待内容完成加载

           await browser.WaitForInitialLoadAsync();


           Console.WriteLine("2加载完成 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));


           //网页截图保存地址

           string imgName = "CefSharp_screenshot" + DateTime.Now.Ticks + ".jpg";

           imgName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), imgName);


           try

           {

               var cefbrowserHost = browser.GetBrowserHost();


               //You can call Invalidate to redraw/refresh the image

               cefbrowserHost.Invalidate(PaintElementType.View);


               //获取内容尺寸

               var contentSize = await browser.GetContentSizeAsync();

               var viewport = new Viewport

               {

                   Height = contentSize.Height,

                   Width = contentSize.Width,

                   Scale = 1.0

               };


               Console.WriteLine("截图...");

               //var buffer = await browser.CaptureScreenshotAsync();


               //完整网页截图

               //var buffer = await browser.CaptureScreenshotAsync(viewport: viewport);

               var buffer = await browser.CaptureScreenshotAsync(CaptureScreenshotFormat.Jpeg, 100, viewport);


               System.IO.File.WriteAllBytes(imgName, buffer);

               Console.WriteLine("截图保存完成");

           }

           catch (Exception ex)

           {

               string msg = ex.Message;

               Console.WriteLine("截图异常:" + msg);

           }


           // We have to wait for something, otherwise the process will exit too soon.

           Console.ReadKey();


           // Clean up Chromium objects. You need to call this in your application otherwise

           // you will get a crash when closing.

           //The ChromiumWebBrowser instance will be disposed

           Cef.Shutdown();



       }



   }



}