一. 引入PuppeteerSharp nuget包;
二. 服务端网页截图方法
public class WebPageUtil { /// <summary> /// 服务端网页截图 /// </summary> /// <param name="url">网页URL</param> /// <param name="sleepSeconds">睡眠秒数:默认两秒,根据网页完整加载所需时间配置</param> /// <param name="viewPortOptions">默认生成移动端的430*932格式</param> /// <returns></returns> public static string WebPageScreenshot(string url,int sleepSeconds=2, ViewPortOptions viewPortOptions = null) { //初始化浏览器 var fetcher = new BrowserFetcher().DownloadAsync("127.0.0.1").Result; string chromePath = App.Configuration["ChromePath"]; chromePath = chromePath.IsNullOrEmpty() ? fetcher.GetExecutablePath() : chromePath; if (!File.Exists(chromePath)) { throw FriendlyException.JNPFException.Oh($"在服务器上未找到Chrome浏览器\n{chromePath}"); } var browser = Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, ExecutablePath = chromePath, DefaultViewport = viewPortOptions ?? new ViewPortOptions { Width = 560, Height = 932, IsMobile = true } }).Result; // 创建一个页面对象 var page = browser.NewPageAsync().Result; // 导航到指定的URL page.GoToAsync(url).Wait(); //等待加载完成后截屏 System.Threading.Thread.Sleep(sleepSeconds * 1000); //截图 FullPage是全屏 string savePath = $"{FileVariable.TemporaryFilePath}{DateTime.Now:yyyyMMddHHmmssfff}.png"; page.ScreenshotAsync(savePath, new ScreenshotOptions() { FullPage = true }).Wait(); page.CloseAsync().Wait(); browser.CloseAsync().Wait(); return savePath; } }
三. 调用截图方法,返回文件地址文件名
/// <summary> /// Web网页截图 /// </summary> /// <param name="url">网页地址</param> /// <param name="sleepSeconds">等待网页完全加载时间(秒)</param> /// <param name="width">截图宽度</param> /// <param name="height">截图高度</param> /// <param name="isMobile">是否移动端网页</param> /// <returns></returns> public FileControlsModel WebPageScreenshot(string url, int sleepSeconds=2, int width= 1920, int height= 1080, bool isMobile= false) { string savePath = WebPageUtil.WebPageScreenshot(url,sleepSeconds,new PuppeteerSharp.ViewPortOptions { Width = width, Height = height, IsMobile = isMobile }); var fileName = _userManager.UserId + "|" + savePath + "|png"; var output = new FileControlsModel { fileId= Path.GetFileName(savePath), name = Path.GetFileName(savePath), url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "JNPF") }; return output; }
标签:截图,网页,string,chromePath,savePath,new,NET,服务端 From: https://www.cnblogs.com/newcxf/p/18175078