SelectPdf for .NET 10 - Asynchronous Html to Pdf Conversion - C# / .NET 10 Sample

This sample shows how to convert web pages to pdf asynchronously, using the ConvertUrlAsync method of the SelectPdf html to pdf converter. The page handler is itself asynchronous: no thread is held while the pages load and render.

The three urls below are converted at the same time and joined into one pdf document. Check the option to convert them one after another instead, for comparison. The time the conversions took is written in the document title (the document properties in the pdf viewer).

Url 1: 

Url 2: 

Url 3: 

Convert one after another

Sample code · C#
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SelectPdf.Universal;

namespace SelectPdf.Samples.Pages
{
    public class AsyncConversionModel : PageModel
    {
        [BindProperty]
        public string TxtUrl1 { get; set; } = "https://selectpdf.com/";

        [BindProperty]
        public string TxtUrl2 { get; set; } = "https://selectpdf.com/pricing/";

        [BindProperty]
        public string TxtUrl3 { get; set; } = "https://selectpdf.com/html-to-pdf-api/";

        [BindProperty]
        public bool ChkOneAfterAnother { get; set; }

        public void OnGet()
        {
        }

        public async Task<IActionResult> OnPostAsync()
        {
            string[] urls = new[] { TxtUrl1, TxtUrl2, TxtUrl3 }
                .Where(url => !string.IsNullOrWhiteSpace(url)).ToArray();

            Stopwatch watch = Stopwatch.StartNew();
            PdfDocument[] docs;

            if (ChkOneAfterAnother)
            {
                // for comparison: each conversion waits for the one before it
                docs = new PdfDocument[urls.Length];
                for (int i = 0; i < urls.Length; i++)
                {
                    HtmlToPdf converter = new HtmlToPdf();
                    converter.Options.NavigationTimeout = Startup.NavigationTimeout;
                    docs[i] = await converter.ConvertUrlAsync(urls[i], HttpContext.RequestAborted);
                }
            }
            else
            {
                // start all conversions, then await them together: the pages load and render at
                // the same time. One converter object per conversion.
                docs = await Task.WhenAll(urls.Select(url =>
                {
                    HtmlToPdf converter = new HtmlToPdf();
                    converter.Options.NavigationTimeout = Startup.NavigationTimeout;
                    return converter.ConvertUrlAsync(url, HttpContext.RequestAborted);
                }));
            }

            watch.Stop();

            // join the converted documents into the first one
            PdfDocument doc = docs[0];
            for (int i = 1; i < docs.Length; i++)
            {
                doc.Append(docs[i]);
            }

            // the time the conversions took, readable in the viewer's document properties
            doc.DocumentInformation.Title = string.Format("{0} pages converted {1} in {2:0.0} seconds",
                urls.Length, ChkOneAfterAnother ? "one after another" : "at the same time",
                watch.Elapsed.TotalSeconds);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf documents
            foreach (PdfDocument d in docs)
            {
                d.Close();
            }

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
        }
    }
}