Click or drag to resize

Asynchronous Conversions

The HTML to PDF converter has asynchronous versions of its conversion methods - GetPdfBytesFromUrlAsync, GetPdfBytesFromHtmlStringAsync, GetPdfDocumentObjectFromUrlAsync, SavePdfFromUrlToFileAsync and the others - that return a Task and take an optional CancellationToken. No thread waits while the page loads and renders, so a web application keeps its threads free for other requests, and several conversions can be awaited together.

Awaiting a conversion
using ExpertPdf.Anywhere.HtmlToPdf;

PdfConverter converter = new PdfConverter();
// converter.LicenseKey = "your license key";
byte[] pdf = await converter.GetPdfBytesFromUrlAsync("https://www.html-to-pdf.info");
File.WriteAllBytes("page.pdf", pdf);

In an ASP.NET Core action, pass the request's cancellation token: when the browser goes away, the conversion stops.

using System.Threading.Tasks;

public async Task<IActionResult> Report(System.Threading.CancellationToken token)
{
    PdfConverter converter = new PdfConverter();
    byte[] pdf = await converter.GetPdfBytesFromUrlAsync(
        "https://www.html-to-pdf.info", token);
    return File(pdf, "application/pdf", "report.pdf");
}
Several conversions at the same time

Start the conversions, then await them together: the pages load and render at the same time. Use one converter object per conversion. The number of conversions that run at once is limited by PdfConverterConcurrencyLevel; the others wait their turn.

string[] urls = { "https://www.html-to-pdf.info", "https://www.example.com" };
Document[] documents = await System.Threading.Tasks.Task.WhenAll(
    System.Linq.Enumerable.Select(urls,
        address => new PdfConverter().GetPdfDocumentObjectFromUrlAsync(address)));

Document merged = new Document();
foreach (Document document in documents)
    merged.AppendDocument(document);
merged.Save("pages.pdf");
merged.Close();
foreach (Document document in documents)
    document.Close();

One converter object runs one conversion at a time. Elements added to a document can be rendered asynchronously too: the AddElementAsync method of pages and templates renders an HTML or image element at once and places it after the elements added before it.

See Also