How to use NewPageAsync method of PuppeteerSharp.Browser class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Browser.NewPageAsync

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

WebBrowser.cs

Source: WebBrowser.cs Github

copy
1using System.IO;
2using System.Threading.Tasks;
3using PuppeteerSharp;
4
5namespace Weikio.ApiFramework.Plugins.Browser
6{
7    public abstract class WebBrowser
8    {
9        protected abstract Task<PuppeteerSharp.Browser> GetBrowser();
10
11        public async Task<FileInfo> Pdf(string url)
12        {
13            using (var browser = await GetBrowser())
14            {
15                using (var page = await browser.NewPageAsync())
16                {
17                    await page.GoToAsync(url);
18                    var bytes = await page.PdfDataAsync(new PdfOptions { MarginOptions = new PuppeteerSharp.Media.MarginOptions { Top = "1cm", Bottom = "1cm" } });
19
20                    var browserPath = ApiFactory.GetBrowserPath();
21                    var pdfPath = Path.Combine(browserPath, "pdf");
22
23                    if (!Directory.Exists(pdfPath))
24                    {
25                        Directory.CreateDirectory(pdfPath);
26                    }
27
28                    var pdfFilePath = Path.Combine(pdfPath, Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".pdf");
29
30                    await File.WriteAllBytesAsync(pdfFilePath, bytes);
31                    var fileInfo = new FileInfo(pdfFilePath);
32
33                    return fileInfo;
34                }
35            }
36        }
37        
38        public async Task<string> Content(string url)
39        {
40            using (var browser = await GetBrowser())
41            {
42                using (var page = await browser.NewPageAsync())
43                {
44                    await page.GoToAsync(url);
45                    var result = await page.GetContentAsync();
46
47                    return result;
48                }
49            }
50        }
51
52        public async Task<byte[]> Screenshot(string url)
53        {
54            using (var browser = await GetBrowser())
55            {
56                using (var page = await browser.NewPageAsync())
57                {
58                    await page.GoToAsync(url);
59                    var result = await page.ScreenshotDataAsync();
60
61                    return result;
62                }
63            }
64        }
65    }
66}
67
Full Screen

DocumentsV2Controller.cs

Source: DocumentsV2Controller.cs Github

copy
1using Microsoft.AspNetCore.Http;
2using Microsoft.AspNetCore.Mvc;
3using Microsoft.Extensions.Logging;
4using PuppeteerSharp;
5using System;
6using System.Collections.Generic;
7using System.Diagnostics;
8using System.IO;
9using System.Linq;
10using System.Threading.Tasks;
11
12namespace PdfService.Controllers {
13	[ApiController]
14	[Route("[controller]")]
15	public class DocumentsV2Controller: ControllerBase {
16		//private readonly LaunchOptions _browserOptions = new LaunchOptions { Headless = true, ExecutablePath = @"C:\Users\Zeroget\Downloads\chrome-win\chrome-win\chrome.exe", Args = new string[] { "--no-sandbox" } };
17		private readonly LaunchOptions _browserOptions = new LaunchOptions { Headless = true, ExecutablePath = @"/usr/bin/chromium-browser", Args = new string[] { "--no-sandbox" } };
18		private static Browser s_browser = null;
19
20		private readonly ILogger<DocumentsV2Controller> _logger;
21
22		public DocumentsV2Controller(ILogger<DocumentsV2Controller> logger) {
23			_logger = logger;
24		}
25
26		[HttpPost("byUrl")]
27		public async Task<IActionResult> Get(List<string> url, bool landscape) {
28			Stopwatch stopwatch = Stopwatch.StartNew();
29			stopwatch.Start();
30			var files = await GeneratePdfAsync(url, landscape);
31			return Ok(new { Paths = files.Select(x => "/pdf/" + x), Elapsed = stopwatch.ElapsedMilliseconds });
32		}
33
34		[HttpPost("byFile")]
35		public async Task<IActionResult> Post(IFormFileCollection fileStream, bool landscape) {
36			Stopwatch stopwatch = Stopwatch.StartNew();
37			stopwatch.Start();
38			var files = await GeneratePdfAsync(fileStream.ToList(), landscape);
39			return Ok(new { Paths = files.Select(x => "/pdf/" + x), Elapsed = stopwatch.ElapsedMilliseconds });
40		}
41
42		[NonAction]
43		public async Task<List<string>> GeneratePdfAsync(List<IFormFile> streams, bool landscape) {
44			s_browser ??= await Puppeteer.LaunchAsync(_browserOptions);
45			var tasks = streams.Select(async x => {
46				using (StreamReader stringReader = new StreamReader(x.OpenReadStream()))
47				using (var page = await s_browser.NewPageAsync()) {
48					await page.SetContentAsync(await stringReader.ReadToEndAsync());
49					var fileName = $"{Guid.NewGuid()}.pdf";
50					await page.PdfAsync($"{Directory.GetCurrentDirectory()}/files/{fileName}", new PdfOptions() { Format = PuppeteerSharp.Media.PaperFormat.A4, Landscape = landscape, OmitBackground = true, PrintBackground = true });
51					return fileName;
52				}
53			});
54
55			var files = await Task.WhenAll(tasks);
56			return files.ToList();
57		}
58
59		[NonAction]
60		public async Task<List<string>> GeneratePdfAsync(List<string> url, bool landscape) {
61			s_browser ??= await Puppeteer.LaunchAsync(_browserOptions);
62			var tasks = url.Select(async x => {
63				using (var page = await s_browser.NewPageAsync()) {
64					await page.GoToAsync(x);
65					var fileName = $"{Guid.NewGuid()}.pdf";
66					await page.PdfAsync($"{Directory.GetCurrentDirectory()}/files/{fileName}", new PdfOptions() { Format = PuppeteerSharp.Media.PaperFormat.A4, Landscape = landscape, OmitBackground = true, PrintBackground = true });
67					return fileName;
68				}
69			});
70
71			var files = await Task.WhenAll(tasks);
72			return files.ToList();
73		}
74	}
75}
76
Full Screen

PdfService.cs

Source: PdfService.cs Github

copy
1using System.IO;
2using System.Threading.Tasks;
3using PuppeteerSharp;
4using PuppeteerSharp.Media;
5
6namespace Foxtrot.Api.Services
7{
8    public class PdfService
9    {
10        private readonly Browser _browser;
11        public PdfService (Browser browser) { _browser = browser; }
12
13        public async Task<Stream> GetPdfFromHtml (string html)
14        {
15            await using var page = await _browser.NewPageAsync();
16            await page.SetContentAsync(html);
17            
18            return await GetPdfStream(page);
19        }
20
21        public async Task<Stream> GetPdfFromUrl (string url)
22        {
23            await using var page = await _browser.NewPageAsync();
24            await page.GoToAsync(url);
25
26            return await GetPdfStream(page);
27        }
28
29        private static async Task<Stream> GetPdfStream (Page page)
30        {
31            return await page.PdfStreamAsync(new PdfOptions
32            {
33                Format = PaperFormat.A4,
34                MarginOptions = new MarginOptions
35                {
36                    Top = "20px",
37                    Right = "20px",
38                    Bottom = "40px",
39                    Left = "20px"
40                },
41            });
42        }
43    }
44}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger NewPageAsync code on LambdaTest Cloud Grid

Execute automation tests with NewPageAsync on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)