XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
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<double>() ?? 1280, 1, 8192);
        var height = Math.Clamp(viewport?["clientHeight"]?.GetValue<double>() ?? 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<string>() ?? throw new IOException("网页截图未返回图像"));
        Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
        await File.WriteAllBytesAsync(path, data, ct);
    }
}