How to use PaperFormat class of PuppeteerSharp.Media package

Best Puppeteer-sharp code snippet using PuppeteerSharp.Media.PaperFormat

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

PdfOptionsConverter.cs

Source: PdfOptionsConverter.cs Github

copy
1using Caracan.Pdf.Models;
2using PuppeteerSharp;
3using PuppeteerSharp.Media;
4
5namespace Caracan.Pdf.Converters
6{
7    public class PdfOptionsConverter : IPdfOptionsConverter
8    {
9        public PdfOptions Convert(Configuration.PdfOptions pdfOptions)
10        {
11            return new PdfOptions
12            {
13                Scale = pdfOptions.Scale,
14                DisplayHeaderFooter = pdfOptions.DisplayHeaderFooter,
15                HeaderTemplate = pdfOptions.HeaderTemplate,
16                FooterTemplate = pdfOptions.FooterTemplate,
17                PrintBackground = pdfOptions.PrintBackground,
18                Landscape = pdfOptions.Landscape,
19                PageRanges = pdfOptions.PageRanges,
20                Format = ConvertFormat(pdfOptions.Format),
21                Width = pdfOptions.Width,
22                Height = pdfOptions.Height,
23                MarginOptions = new PuppeteerSharp.Media.MarginOptions {
24                    Top = pdfOptions.MarginOptions.Top,
25                    Bottom = pdfOptions.MarginOptions.Bottom,
26                    Left = pdfOptions.MarginOptions.Left,
27                    Right = pdfOptions.MarginOptions.Right
28                },
29                PreferCSSPageSize = pdfOptions.PreferCSSPageSize
30            };
31        }
32
33        private PaperFormat ConvertFormat(Format format)
34        {
35            switch (format.Type)
36            {
37                case FormatType.A0:
38                    return PaperFormat.A0;
39                case FormatType.A1:
40                    return PaperFormat.A1;
41                case FormatType.A2:
42                    return PaperFormat.A2;
43                case FormatType.A3:
44                    return PaperFormat.A3;
45                case FormatType.A4:
46                    return PaperFormat.A4;
47                case FormatType.A5:
48                    return PaperFormat.A5;
49                case FormatType.A6:
50                    return PaperFormat.A6;
51
52                case FormatType.Letter:
53                    return PaperFormat.Letter;
54                case FormatType.Legal:
55                    return PaperFormat.Legal;
56                case FormatType.Ledger:
57                    return PaperFormat.Ledger;
58                case FormatType.Tabloid:
59                    return PaperFormat.Tabloid;
60
61                default:
62                    return new PaperFormat(format.Width, format.Height);
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

HtmlToPdfConverter.cs

Source: HtmlToPdfConverter.cs Github

copy
1using PuppeteerSharp;
2using PuppeteerSharp.Media;
3using System.Diagnostics;
4using System.IO;
5using System.Runtime.InteropServices;
6using System.Threading.Tasks;
7
8namespace CvGenerator.Logic
9{
10    public class HtmlToPdfConverter
11    {
12        private readonly Browser browser;
13
14        public HtmlToPdfConverter()
15        {
16            var downloadTask = Task.Run(() => new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision));
17            downloadTask.Wait();
18            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
19            {
20                var path = Launcher.GetExecutablePath();
21                Bash($"chmod 777 {path}");
22            }
23            browser = Task.Run(() => Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, Args = new string[] { "--no-sandbox" } })).Result;
24        }
25
26        private void Bash(string cmd)
27        {
28            var escapedArgs = cmd.Replace("\"", "\\\"");
29
30            var process = new Process()
31            {
32                StartInfo = new ProcessStartInfo
33                {
34                    FileName = "/bin/bash",
35                    Arguments = $"-c \"{escapedArgs}\"",
36                    RedirectStandardOutput = true,
37                    UseShellExecute = false,
38                    CreateNoWindow = true,
39                }
40            };
41            process.Start();
42            string result = process.StandardOutput.ReadToEnd();
43            process.WaitForExit();
44        }
45
46        public async Task<byte[]> ConvertToPdf(string resPath, string html, PaperFormat paperFormat, int margin = 32, decimal scale = 1)
47        {
48            using (var page = await browser.NewPageAsync())
49            {
50                if(resPath != null)
51                    await page.GoToAsync(resPath);
52                await page.SetContentAsync(html);
53
54                string marginStr = margin + "px";
55                var pdfOptions = new PdfOptions
56                {
57                    Format = paperFormat,
58                    MarginOptions = new MarginOptions
59                    {
60                        Left = marginStr,
61                        Right = marginStr,
62                        Top = marginStr,
63                        Bottom = marginStr
64                    },
65                    Scale = scale,
66                    PrintBackground = true,
67                };
68
69                return await page.PdfDataAsync(pdfOptions);
70            }
71        }
72    }
73}
74
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

Most used methods in PaperFormat

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

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)