.NET服务端网页截图
一. 引入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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!