using Microsoft.Web.WebView2.Core; using System.Text.Json.Nodes; namespace XFEWorkflow.Controls; internal static class WebViewCapture { public static async Task SaveAsync(CoreWebView2 web, string path, CancellationToken ct = default, bool fromSurface = false) { var metrics = await web.CallDevToolsProtocolMethodAsync("Page.getLayoutMetrics", "{}").AsTask(ct); var viewport = JsonNode.Parse(metrics)?["cssVisualViewport"]; var width = Math.Clamp(viewport?["clientWidth"]?.GetValue() ?? 1280, 1, 8192); var height = Math.Clamp(viewport?["clientHeight"]?.GetValue() ?? 720, 1, 8192); var options = new JsonObject { ["format"] = "png", ["fromSurface"] = fromSurface, ["captureBeyondViewport"] = true, ["clip"] = new JsonObject { ["x"] = 0, ["y"] = 0, ["width"] = width, ["height"] = height, ["scale"] = 1 } }; var json = await web.CallDevToolsProtocolMethodAsync("Page.captureScreenshot", options.ToJsonString()).AsTask(ct).WaitAsync(TimeSpan.FromSeconds(20), ct); var data = Convert.FromBase64String(JsonNode.Parse(json)?["data"]?.GetValue() ?? throw new IOException("网页截图未返回图像")); Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!); await File.WriteAllBytesAsync(path, data, ct); } }