使用工具可以保存可见区域
CallDevToolsProtocolMethodAsync("Page.captureScreenshot", Params) always returns only visible part of html page including scrollbars. I tried all possible combinations of "fromSurface" and "captureBeyondViewport" values, no difference. I'm using 1.0.705.50 WinForms.
使用下面方法最终解决
public async Task<Image> TakeWebScreenshot(bool currentControlClipOnly = false)
{
dynamic scl = null;
Size siz;
if (!currentControlClipOnly)
{
var res = await wv2.CoreWebView2.ExecuteScriptAsync(@"var v = {""w"":document.body.scrollWidth, ""h"":document.body.scrollHeight}; v;");
try{ scl = JObject.Parse(res); }catch{}
}
siz = scl != null ?
new Size( (int)scl.w > wv2.Width ? (int)scl.w : wv2.Width,
(int)scl.h > wv2.Height ? (int)scl.h : wv2.Height )
:
wv2.Size;
var img = await GetWebBrowserBitmap(siz);
return img;
}
private async Task<Bitmap> GetWebBrowserBitmap(Size clipSize)
{
dynamic clip = new JObject();
clip.x = 0;
clip.y = 0;
clip.width = clipSize.Width;
clip.height = clipSize.Height;
clip.scale = 1;
dynamic settings = new JObject();
settings.format = "jpeg";
settings.clip = clip;
settings.fromSurface = true;
settings.captureBeyondViewport = true;
var p = settings.ToString(Newtonsoft.Json.Formatting.None);
var devData = await wv2.CoreWebView2.CallDevToolsProtocolMethodAsync("Page.captureScreenshot", p);
var imgData = (string)((dynamic)JObject.Parse(devData)).data;
var ms = new MemoryStream(Convert.FromBase64String(imgData));
return (Bitmap)Image.FromStream(ms);
}