The HTML conversion to PDF happens in two main stages. In the first stage the HTML document is loaded in the internal HTML viewer. When the load is complete the second stage starts and the HTML content is rendered to PDF document or into an image. The moment when the HTML load is complete is not well defined for all HTML documents. There might be for example scripts running in page which continuously update the HTML document. The triggering modes help the converter to decide when the HTML page load should be considered completed and when the actual rendering to PDF can start. The triggering mode is given by the HtmlToPdfConverterTriggeringMode property. There are two possible triggering modes:
Auto Triggering Mode - this is the default triggering mode and the rendering to PDF starts immediately after the HTML page is loaded in converter which means the images, script files, CSS files are loaded and the scripts found in page are executed. The scripts can actually schedule asynchronous operations to be executed later, but the converter will not wait for those operations to finish. You can use a conversion delay or the Manual triggering mode, described below, to handle those asynchronous operations. The code sample for settings this triggering mode is below.
// Create the PDF converter
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set the triggering mode
htmlToPdfConverter.TriggeringMode = TriggeringMode.Auto;Optionally it is possible to set the converter to wait an additional given time period for the asynchronous scripts to be executed before starting the rendering to PDF or to image. The code sample below will configure the converter to start rendering at 3 seconds after the HTML page was loaded which means the asynchronous scripts may run for 3 more seconds before the actual rendering to PDF or image starts. The conversion delay is useful when you know that all the asynchronous scripts will finish execution in a given period of time.
// Create the PDF converter
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set a conversion delay in seconds
htmlToPdfConverter.ConversionDelay = 3;Manual Triggering Mode - When this triggering mode is set the converter will wait until the evoPdfConverter_startConversion() method is called from HTML page JavaScript. The code sample below will configure the converter for manual rendering mode.
// Create the PDF converter
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set the triggering mode
htmlToPdfConverter.TriggeringMode = TriggeringMode.Manual;ScriptToExecuteAfterLoad is a script executed in the page after it was loaded, before the conversion starts; it can fill fields, click buttons or add content. With WaitForAfterLoadScript set to true the conversion waits for the script to finish, so the script can await asynchronous operations; otherwise the conversion continues while the script runs.
htmlToPdfConverter.ScriptToExecuteAfterLoad =
"await new Promise(resolve => setTimeout(resolve, 2000));" +
"document.body.insertAdjacentHTML('beforeend', '<p>Added by the script executed after load</p>');";
htmlToPdfConverter.WaitForAfterLoadScript = true;using System;
using System.IO;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using EvoPdf_Next_AspNetDemo.Models;
using EvoPdf_Next_AspNetDemo.Models.HTML_to_PDF;
// Use EVO PDF Namespace
using EvoPdf.Next;
namespace EvoPdf_Next_AspNetDemo.Controllers.HTML_to_PDF
{
public class Conversion_Triggering_ModesController : Controller
{
private readonly IWebHostEnvironment m_hostingEnvironment;
public Conversion_Triggering_ModesController(IWebHostEnvironment hostingEnvironment)
{
m_hostingEnvironment = hostingEnvironment;
}
// GET: Conversion_Triggering_Modes
public ActionResult Index()
{
var model = SetViewModel();
return View(model);
}
[HttpPost]
public ActionResult ConvertHtmlToPdf(Conversion_Triggering_Modes_ViewModel model)
{
if (!ModelState.IsValid)
{
var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
throw new ValidationException(errorMessage);
}
// Set the license key received after purchase to use the library in licensed mode; leave it commented for demo mode
// Licensing.LicenseKey = "your-license-key";
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set the conversion triggering mode
if (model.TriggeringMode == "Auto")
{
// Set Auto triggering mode
htmlToPdfConverter.TriggeringMode = TriggeringMode.Auto;
// Optionally set a delay
htmlToPdfConverter.ConversionDelay = model.ConversionDelay;
}
else if (model.TriggeringMode == "Manual")
{
// Set manual triggering mode
// The conversion starts when the evoPdfConverter_startConversion() function is called
// in JavaScript code of the converted HTML page
htmlToPdfConverter.TriggeringMode = TriggeringMode.Manual;
}
if (model.ExecuteScriptAfterLoad && !string.IsNullOrWhiteSpace(model.AfterLoadScript))
{
// A script executed in the page after it was loaded, before the conversion starts; it can fill fields,
// click buttons or add content. The conversion waits for the script to finish when the flag is set, so
// the script can await asynchronous operations; otherwise the conversion continues while the script runs
htmlToPdfConverter.ScriptToExecuteAfterLoad = model.WaitForAfterLoadScript
? model.AfterLoadScript
: "(async () => { " + model.AfterLoadScript + " })();";
htmlToPdfConverter.WaitForAfterLoadScript = model.WaitForAfterLoadScript;
}
byte[] outPdfBuffer = null;
if (model.HtmlPageSource == "Html")
{
string htmlWithForm = model.HtmlString;
string baseUrl = model.BaseUrl;
// Convert the HTML string with page-break-inside:avoid styles to a PDF document in a memory buffer
outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlWithForm, baseUrl);
}
else
{
string url = model.Url;
// Convert the HTML page with page-break-inside:avoid styles to a PDF document in a memory buffer
outPdfBuffer = htmlToPdfConverter.ConvertUrl(url);
}
// Send the PDF file to browser
FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
fileResult.FileDownloadName = "Conversion_Triggering_Modes.pdf";
return fileResult;
}
private Conversion_Triggering_Modes_ViewModel SetViewModel()
{
var model = new Conversion_Triggering_Modes_ViewModel();
var contentRootPath = Path.Combine(m_hostingEnvironment.ContentRootPath, "wwwroot");
HttpRequest request = ControllerContext.HttpContext.Request;
UriBuilder uriBuilder = new UriBuilder();
uriBuilder.Scheme = request.Scheme;
uriBuilder.Host = request.Host.Host;
if (request.Host.Port != null)
uriBuilder.Port = (int)request.Host.Port;
uriBuilder.Path = request.PathBase.ToString() + request.Path.ToString();
uriBuilder.Query = request.QueryString.ToString();
string currentPageUrl = uriBuilder.Uri.AbsoluteUri;
string rootUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Conversion_Triggering_Modes".Length);
model.HtmlString = System.IO.File.ReadAllText(Path.Combine(contentRootPath, "DemoAppFiles/Input/HTML_Files/Triggering_Modes.html"));
model.BaseUrl = rootUrl + "DemoAppFiles/Input/HTML_Files/";
model.Url = rootUrl + "DemoAppFiles/Input/HTML_Files/Triggering_Modes.html";
return model;
}
}
}<!DOCTYPE html>
<html>
<head>
<title>Conversion Triggering Modes</title>
<link href="styles/webfonts.css" type="text/css" rel="stylesheet">
<script type="text/javascript">
var counter = 0;
function count() {
// Display the current counter value
document.getElementById("counterDiv").innerHTML = counter;
if (typeof evoPdfConverter_startConversion == 'function' && counter == 5) {
// Trigger conversion when counter reached a value
counterDiv.style.color = "green";
evoPdfConverter_startConversion();
}
else {
// Increment counter
counter++;
// After 1 second and call count() again
setTimeout("count()", 1000);
}
}
</script>
</head>
<body onload="count()" style="font-family: Verdana, sans-serif; font-size: 14px ">
The <span style="color: green"><b>count()</b></span> function is called immediately after the HTML page was loaded as a handler of the <span style="color: blue"><b>onload event</b></span> of the body element. The
<span style="color: green"><b>count()</b></span> function increments the counter and schedules a new call to the same function to occur after 1 second if the counter did not reach the value 5 yet.<br />
<ul>
<li>
If the selected triggering mode is <span style="background-color: aliceblue"><b>Auto</b></span> then the <span style="color: green">count()</span> will be invoked once a second during the given delay interval and after that the conversion to PDF will start
</li>
<li>
If the selected triggering mode is <span style="background-color: aliceblue"><b>Manual</b></span> then the <span style="color: green">count()</span> will be invoked once a second until the counter reached the value 5. When the counter reached this value the
<span style="background-color: whitesmoke"><b>evoPdfConverter_startConversion()</b></span> function is called to trigger the conversion to PDF
</li>
</ul>
<br />
<b style="font-size: 30px">Counter value:</b>
<span style="font-size: 30px; color: red" id="counterDiv">0</span>
<br />
<br />
<br />
<span style="color: navy">
<script type="text/javascript">
if (typeof evoPdfInfo != "undefined") {
document.write("Created by " + evoPdfInfo.Version);
}
</script>
</span>
</body>
</html>