Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.ScreenshotBase64Async
DesignController.cs
Source:DesignController.cs  
...418                                        Width = width + "px",419                                        Height = (int)double.Parse(height) + 3000 + "px",420                                    });421422                                    string b = await pages2[i].ScreenshotBase64Async(new ScreenshotOptions()423                                    {424                                        Clip = new PuppeteerSharp.Media.Clip()425                                        {426                                            Width = decimal.Parse(width),427                                            Height = decimal.Parse(height),428                                        },429                                        OmitBackground = true,430                                    });431432                                    reader2[i] = new PdfReader(a);433                                    Rectangle rec = reader2[i].GetPageSize(1);434                                    float ratio = (int)double.Parse(width) * 1f / (int)double.Parse(height);435                                    float left = 0;436                                    float bottom = rec.Height - rec.Width / ratio;
...ElementHandle.cs
Source:ElementHandle.cs  
...88        /// </summary>89        /// <returns>Task which resolves to a <see cref="byte"/>[] containing the image data.</returns>90        /// <param name="options">Screenshot options.</param>91        public async Task<byte[]> ScreenshotDataAsync(ScreenshotOptions options)92            => Convert.FromBase64String(await ScreenshotBase64Async(options).ConfigureAwait(false));93        /// <summary>94        /// This method scrolls element into view if needed, and then uses <seealso cref="Page.ScreenshotBase64Async(ScreenshotOptions)"/> to take a screenshot of the element. 95        /// If the element is detached from DOM, the method throws an error.96        /// </summary>97        /// <returns>Task which resolves to a <see cref="string"/> containing the image data as base64.</returns>98        public Task<string> ScreenshotBase64Async() => ScreenshotBase64Async(new ScreenshotOptions());99        /// <summary>100        /// This method scrolls element into view if needed, and then uses <seealso cref="Page.ScreenshotBase64Async(ScreenshotOptions)"/> to take a screenshot of the element. 101        /// If the element is detached from DOM, the method throws an error.102        /// </summary>103        /// <returns>Task which resolves to a <see cref="string"/> containing the image data as base64.</returns>104        /// <param name="options">Screenshot options.</param>105        public async Task<string> ScreenshotBase64Async(ScreenshotOptions options)106        {107            var needsViewportReset = false;108            var boundingBox = await BoundingBoxAsync().ConfigureAwait(false);109            if (boundingBox == null)110            {111                throw new PuppeteerException("Node is either not visible or not an HTMLElement");112            }113            var viewport = Page.Viewport;114            if (viewport != null && (boundingBox.Width > viewport.Width || boundingBox.Height > viewport.Height))115            {116                var newRawViewport = JObject.FromObject(viewport);117                newRawViewport.Merge(new ViewPortOptions118                {119                    Width = (int)Math.Max(viewport.Width, Math.Ceiling(boundingBox.Width)),120                    Height = (int)Math.Max(viewport.Height, Math.Ceiling(boundingBox.Height))121                });122                await Page.SetViewportAsync(newRawViewport.ToObject<ViewPortOptions>()).ConfigureAwait(false);123                needsViewportReset = true;124            }125            await ExecutionContext.EvaluateFunctionAsync(@"function(element) {126                element.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant'});127            }", this).ConfigureAwait(false);128            await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);129            boundingBox = await BoundingBoxAsync().ConfigureAwait(false);130            if (boundingBox == null)131            {132                throw new PuppeteerException("Node is either not visible or not an HTMLElement");133            }134            var getLayoutMetricsResponse = await Client.SendAsync<GetLayoutMetricsResponse>("Page.getLayoutMetrics").ConfigureAwait(false);135            var clip = boundingBox;136            clip.X += getLayoutMetricsResponse.LayoutViewport.PageX;137            clip.Y += getLayoutMetricsResponse.LayoutViewport.PageY;138            options.Clip = boundingBox.ToClip();139            var imageData = await Page.ScreenshotBase64Async(options).ConfigureAwait(false);140            if (needsViewportReset)141            {142                await Page.SetViewportAsync(viewport).ConfigureAwait(false);143            }144            return imageData;145        }146        /// <summary>147        /// Scrolls element into view if needed, and then uses <see cref="Page.Mouse"/> to hover over the center of the element.148        /// </summary>149        /// <returns>Task which resolves when the element is successfully hovered</returns>150        public async Task HoverAsync()151        {152            await ScrollIntoViewIfNeededAsync().ConfigureAwait(false);153            var (x, y) = await ClickablePointAsync().ConfigureAwait(false);...Methods.cs
Source:Methods.cs  
...180        {181            data.Logger.LogHeader();182            var frame = GetFrame(data);183            var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];184            var base64 = await elem.ScreenshotBase64Async(new PuppeteerSharp.ScreenshotOptions { FullPage = fullPage, OmitBackground = omitBackground });185            data.Logger.Log($"Took a screenshot of the element as base64", LogColors.DarkSalmon);186            return base64;187        }188        [Block("Switches to a different iframe", name = "Switch to Frame")]189        public static async Task PuppeteerSwitchToFrame(BotData data, FindElementBy findBy, string identifier, int index)190        {191            data.Logger.LogHeader();192            var frame = GetFrame(data);193            var elem = (await frame.QuerySelectorAllAsync(BuildSelector(findBy, identifier)))[index];194            data.Objects["puppeteerFrame"] = await elem.ContentFrameAsync();195            data.Logger.Log($"Switched to iframe", LogColors.DarkSalmon);196        }197        [Block("Waits for an element to appear on the page", name = "Wait for Element")]198        public static async Task PuppeteerWaitForElement(BotData data, FindElementBy findBy, string identifier, bool hidden = false, bool visible = true,...ScreenshotTests.cs
Source:ScreenshotTests.cs  
...249                    Width = 500,250                    Height = 500251                });252                await page.GoToAsync(TestConstants.ServerUrl + "/grid.html");253                var screenshot = await page.ScreenshotBase64Async();254                Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", Convert.FromBase64String(screenshot)));255            }256        }257        [Fact]258        public void ShouldInferScreenshotTypeFromName()259        {260            Assert.Equal(ScreenshotType.Jpeg, ScreenshotOptions.GetScreenshotTypeFromFile("Test.jpg"));261            Assert.Equal(ScreenshotType.Jpeg, ScreenshotOptions.GetScreenshotTypeFromFile("Test.jpe"));262            Assert.Equal(ScreenshotType.Jpeg, ScreenshotOptions.GetScreenshotTypeFromFile("Test.jpeg"));263            Assert.Equal(ScreenshotType.Png, ScreenshotOptions.GetScreenshotTypeFromFile("Test.png"));264            Assert.Null(ScreenshotOptions.GetScreenshotTypeFromFile("Test.exe"));265        }266        [Fact]267        public async Task ShouldWorkWithQuality()...VisualRenderWorker.cs
Source:VisualRenderWorker.cs  
...68                        ? 3000 69                        : int.Parse(_browserDelayMilis));70                    var container = await page.QuerySelectorAsync("#report-container");71                    // var container = await page.Frames[1].WaitForSelectorAsync("content explorationContainer newPaneColors contentReady");72                    string imageData = await container.ScreenshotBase64Async();73                    await ((BotAdapter)_adapter).ContinueConversationAsync(74                        _appId, 75                        msg.ConversationReference, 76                        async (context, token) => 77                        {78                            IMessageActivity activity = MessageFactory.Attachment(new Attachment()79                                {80                                    Name = "result.png",81                                    ContentType = "image/png",82                                    ContentUrl = $"data:image/png;base64,{imageData}"83                                });84                            await context.SendActivityAsync(activity, token);85                        }, 86                        default(CancellationToken));...CaptureService.cs
Source:CaptureService.cs  
...67                    await Console.Out.WriteLineAsync($"RESPONSE: {e.Response.Url} -({e.Response.Request.Method}) {e.Response.Status:d} {e.Response.StatusText}");68                };69                await page.GoToAsync(url, WaitUntilNavigation.Networkidle0);70                var htmlData = await page.GetContentAsync();71                var pageData = await page.ScreenshotBase64Async(new ScreenshotOptions{Type= ScreenshotType.Jpeg, Quality= 100});72                return new CaptureReply73                {74                    Message = pageData,75                    Html = htmlData76                };77            }78        }79    }80}...ScreenshotOptions.cs
Source:ScreenshotOptions.cs  
...55        /// };56        /// await page.GoToAsync("https://www.google.com");57        /// for(var x = 0; x < 100; x++)58        /// {59        ///     await page.ScreenshotBase64Async(screenShotOptions);60        /// }61        /// await page.SetBurstModeOffAsync();62        /// ]]></example>63        [JsonIgnore]64        public bool BurstMode { get; set; } = false;65        internal static ScreenshotType? GetScreenshotTypeFromFile(string file)66        {67            var extension = new FileInfo(file).Extension.Replace(".", string.Empty);68            _extensionScreenshotTypeMap.TryGetValue(extension, out var result);69            return result;70        }71    }72}...ScreenService.cs
Source:ScreenService.cs  
...12                Headless = true13            });14            var page = await browser.NewPageAsync();15            await page.GoToAsync(url);16            return await page.ScreenshotBase64Async(new ScreenshotOptions{Type= ScreenshotType.Jpeg, Quality= 100});17        }18    }19}...ScreenshotBase64Async
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7{8    {9        static void Main(string[] args)10        {11            MainAsync().Wait();12        }13        static async Task MainAsync()14        {15            var browser = await Puppeteer.LaunchAsync(new LaunchOptions16            {17                Args = new string[] { "--no-sandbox" }18            });19            var page = await browser.NewPageAsync();20            var base64 = await page.ScreenshotBase64Async();21            Console.WriteLine(base64);22            await browser.CloseAsync();23        }24    }25}26using PuppeteerSharp;27using System;28using System.Collections.Generic;29using System.IO;30using System.Linq;31using System.Text;32using System.Threading.Tasks;33{34    {35        static void Main(string[] args)36        {37            MainAsync().Wait();38        }39        static async Task MainAsync()40        {41            var browser = await Puppeteer.LaunchAsync(new LaunchOptions42            {43                Args = new string[] { "--no-sandbox" }44            });45            var page = await browser.NewPageAsync();46            var stream = await page.ScreenshotStreamAsync();47            using (var fileStream = new FileStream("screenshot.png", FileMode.Create))48            {49                await stream.CopyToAsync(fileStream);50            }51            await browser.CloseAsync();52        }53    }54}55using PuppeteerSharp;56using System;57using System.Collections.Generic;58using System.IO;59using System.Linq;60using System.Text;61using System.Threading.Tasks;62{63    {64        static void Main(string[] args)65        {66            MainAsync().Wait();67        }68        static async Task MainAsync()69        {70            var browser = await Puppeteer.LaunchAsync(new LaunchOptions71            {72                Args = new string[] { "--no-sandbox" }73            });ScreenshotBase64Async
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            var options = new LaunchOptions { Headless = true };9            using (var browser = await Puppeteer.LaunchAsync(options))10            using (var page = await browser.NewPageAsync())11            {12                await page.GoToAsync("ScreenshotBase64Async
Using AI Code Generation
1{2    {3        public static async Task<string> ScreenshotBase64Async(Page page)4        {5            var options = new ScreenshotOptions { FullPage = true };6            var screenshot = await page.ScreenshotDataAsync(options);7            var base64 = Convert.ToBase64String(screenshot);8            return base64;9        }10    }11}12using PuppeteerSharp;13using System;14using System.Threading.Tasks;15{16    {17        public static async Task<string> ScreenshotBase64Async(Page page)18        {19            var options = new ScreenshotOptions { FullPage = true };20            var screenshot = await page.ScreenshotDataAsync(options);21            var base64 = Convert.ToBase64String(screenshot);22            return base64;23        }24    }25}26using PuppeteerSharp;27using System;28using System.Threading.Tasks;29{30    {31        public static async Task<string> ScreenshotBase64Async(Page page)32        {33            var options = new ScreenshotOptions { FullPage = true };34            var screenshot = await page.ScreenshotDataAsync(options);35            var base64 = Convert.ToBase64String(screenshot);36            return base64;37        }38    }39}40using PuppeteerSharp;41using System;42using System.Threading.Tasks;43{44    {45        public static async Task<string> ScreenshotBase64Async(Page page)46        {47            var options = new ScreenshotOptions { FullPage = true };48            var screenshot = await page.ScreenshotDataAsync(options);49            var base64 = Convert.ToBase64String(screenshot);50            return base64;51        }52    }53}54using PuppeteerSharp;55using System;56using System.Threading.Tasks;57{58    {59        public static async Task<string> ScreenshotBase64Async(Page page)Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
