async Task NavigationComplete(WKWebView webView, string filename, PageSize pageSize, PageMargin margin, TaskCompletionSource <ToFileResult> taskCompletionSource) { try { var widthString = await webView.EvaluateJavaScriptAsync("document.documentElement.offsetWidth"); var width = double.Parse(widthString.ToString()); var heightString = await webView.EvaluateJavaScriptAsync("document.documentElement.offsetHeight"); var height = double.Parse(heightString.ToString()); if (width < 1 || height < 1) { taskCompletionSource.SetResult(new ToFileResult(true, "WebView has zero width or height")); return; } webView.ClipsToBounds = false; webView.ScrollView.ClipsToBounds = false; var bounds = webView.Bounds; webView.Bounds = new CGRect(0, 0, (nfloat)width, (nfloat)height); var scale = pageSize.Width / width; var snapshotConfig = new WKSnapshotConfiguration { SnapshotWidth = pageSize.Width / Display.Scale }; var image = await webView.TakeSnapshotAsync(snapshotConfig); if (image.AsPNG() is NSData data) { var path = Path.Combine(ToPngService.FolderPath(), filename + ".png"); File.WriteAllBytes(path, data.ToArray()); taskCompletionSource.SetResult(new ToFileResult(false, path)); return; } webView.Bounds = bounds; taskCompletionSource.SetResult(new ToFileResult(true, "No data returned.")); } catch (Exception e) { taskCompletionSource.SetResult(new ToFileResult(true, "Exception: " + e.Message + (e.InnerException != null ? "Inner exception: " + e.InnerException.Message : null))); } finally { webView.Dispose(); } }