Click or drag to resize
Pdf Library for .NET

Asynchronous Conversion

SelectPdf Html To Pdf Converter for .NET - Community Edition can convert asynchronously. While a web page loads and renders, no thread is held waiting for it, so a web application can have many conversions in flight without a thread for each, and several pages can be rendered at the same time from one method with await Task.WhenAll(...).

An asynchronous conversion produces the same document as the synchronous one. The asynchronous methods are:

  • ConvertUrlAsync - converts a web page, with an overload that takes a CancellationToken.

  • ConvertHtmlStringAsync - converts a html string, with or without a base url, and with overloads that take a CancellationToken.

Converting several pages at the same time

One HtmlToPdf object runs one conversion at a time: use a converter for each conversion that runs at the same time. Conversions started together render at the same time, up to MaximumConcurrentConversions; the ones past that limit wait for their turn in the order they were started, in the same queue as the synchronous conversions.

string[] urls =
{
    "https://selectpdf.com",
    "https://selectpdf.com/pricing/",
    "https://selectpdf.com/html-to-pdf-api/"
};

PdfDocument[] docs = await Task.WhenAll(urls.Select(url =>
{
    HtmlToPdf converter = new HtmlToPdf();
    converter.Options.PdfPageSize = PdfPageSize.A4;
    return converter.ConvertUrlAsync(url);
}));

for (int i = 0; i < docs.Length; i++)
{
    docs[i].Save("page" + i + ".pdf");
    docs[i].Close();
}

A conversion with html in its header or footer (PdfHtmlSection) renders the header and the footer beside the page itself, synchronously or not, so they add little to the conversion time.

Cancelling a conversion

Cancelling the token stops the conversion wherever it is: a conversion still waiting for its turn leaves the queue, and one that is rendering is stopped in the engine. The task then ends cancelled and no document is produced. A token with a timeout is a simple way to bound how long a conversion may take.

using (CancellationTokenSource timeout =
    new CancellationTokenSource(TimeSpan.FromSeconds(30)))
{
    HtmlToPdf converter = new HtmlToPdf();
    try
    {
        PdfDocument doc =
            await converter.ConvertUrlAsync("https://selectpdf.com", timeout.Token);
        doc.Save("document.pdf");
        doc.Close();
    }
    catch (OperationCanceledException)
    {
        // the conversion took longer than 30 seconds
    }
}
See Also