The web page you want to convert might be protected by different types of authentication. The most common authentication methods are Integrated Windows Authentication, Forms Authentication and custom Login pages. Winnovative HTML to PDF Converter offers support for resolving all these types of authentication.
The converter will automatically use the credentials of the user running the converter to resolve the NTLM authentication. This user can be the currently logged in user when using the converter in a desktop application or the user set as IIS pool identity when using the converter in an ASP.NET application. If the default automatic credentials cannot resolve the authentication you have the possibility to explicitly set the Username and Password in HtmlToPdfConverterAuthenticationOptions, HtmlToPdfElementAuthenticationOptions, HtmlToImageConverterAuthenticationOptions, HtmlToImageElementAuthenticationOptions or HtmlToSvgConverterAuthenticationOptions objects, function of the interface you are using to convert HTML to PDF or to images.
// Create the HTML to PDF converter
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set authentication options
htmlToPdfConverter.AuthenticationOptions.Username = username;
htmlToPdfConverter.AuthenticationOptions.Password = password;
// Create a HTML to PDF element
HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement();
// Set authentication options
htmlToPdfElement.AuthenticationOptions.Username = username;
htmlToPdfElement.AuthenticationOptions.Password = password;
// Create the HTML to Image converter
HtmlToImageConverter htmlToImageConverter = new HtmlToImageConverter();
// Set authentication options
htmlToImageConverter.AuthenticationOptions.Username = username;
htmlToImageConverter.AuthenticationOptions.Password = password;
// Create a HTML to Image element
HtmlToImageElement htmlToImageElement = new HtmlToImageElement();
// Set authentication options
htmlToImageElement.AuthenticationOptions.Username = username;
htmlToImageElement.AuthenticationOptions.Password = password;
// Create the HTML to SVG converter
HtmlToSvgConverter htmlToSvgConverter = new HtmlToSvgConverter();
// Set authentication options
htmlToSvgConverter.AuthenticationOptions.Username = username;
htmlToSvgConverter.AuthenticationOptions.Password = password;
The cookie based authentication implementation usually stores the authentication ticket in a cookie which should be sent back to server each time a resource is requested. The authentication cookies can be sent back to server using the HtmlToPdfConverterHttpRequestCookies, HtmlToPdfElementHttpRequestCookies, HtmlToImageConverterHttpRequestCookies, HtmlToImageElementHttpRequestCookies or HtmlToSvgConverterHttpRequestCookies properties, function of the interface you are using to convert HTML to PDF or to images.
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Add the authentication cookie to request
if (ControllerContext.HttpContext.Request.Cookies[AuthCookieName] != null)
{
htmlToPdfConverter.HttpRequestCookies.Add(AuthCookieName,
ControllerContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
}
htmlToPdfConverter.ConvertUrl(urlToConvert);
Authentication implemented at application level using a login page can be resolved by getting the HTML code of the web page to be converted and then convert that string to PDF.
However, the CSS files and images referenced by the HTML code to be converted should be placed in a location which doesn't require authentication or otherwise you'll have combine with one of the authentication methods above to resolve the resources.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.IO;
// Use Winnovative Namespace
using Winnovative;
namespace WnvHtmlToPdfDemo.Controllers
{
public class Convert_Page_in_Same_SessionController : Controller
{
private ICompositeViewEngine m_viewEngine;
public Convert_Page_in_Same_SessionController(ICompositeViewEngine viewEngine)
{
m_viewEngine = viewEngine;
}
// GET: Convert_Page_in_Same_Session
public ActionResult Index()
{
ViewData.Add("firstName", "John");
ViewData.Add("lastName", "Smith");
ViewData.Add("gender", "maleRadioButton");
ViewData.Add("haveCar", "true");
ViewData.Add("carType", "Volvo");
ViewData.Add("comments", "My comments\r\nLine 1\r\nLine 2");
return View();
}
public ActionResult Display_Session_Variables()
{
return View();
}
[HttpPost]
public ActionResult ConvertPageInSameSessionToPdf(IFormCollection collection)
{
ViewDataDictionary viewData = new ViewDataDictionary(ViewData);
viewData.Clear();
// transmit the posted data to view
viewData.Add("firstName", collection["firstNameTextBox"]);
viewData.Add("lastName", collection["lastNameTextBox"]);
viewData.Add("gender", collection["gender"]);
viewData.Add("haveCar", collection["haveCarCheckBox"]);
viewData.Add("carType", collection["carTypeDropDownList"]);
viewData.Add("comments", collection["commentsTextBox"]);
// The string writer where to render the HTML code of the view
StringWriter stringWriter = new StringWriter();
// Render the Index view in a HTML string
ViewEngineResult viewResult = m_viewEngine.FindView(ControllerContext, "Display_Session_Variables", false);
ViewContext viewContext = new ViewContext(
ControllerContext,
viewResult.View,
viewData,
TempData,
stringWriter,
new HtmlHelperOptions()
);
Task renderTask = viewResult.View.RenderAsync(viewContext);
renderTask.Wait();
// Get the view HTML string
string htmlToConvert = stringWriter.ToString();
// Get the base URL
HttpRequest request = this.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 baseUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Convert_Page_in_Same_Session/ConvertPageInSameSessionToPdf".Length);
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";
// Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed
// Set this property to 0 if you don't need to wait for such asynchcronous operations to finish
htmlToPdfConverter.ConversionDelay = 2;
// Convert the HTML string to a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlToConvert, baseUrl);
// Send the PDF file to browser
FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
fileResult.FileDownloadName = "Convert_Page_in_Same_Session.pdf";
return fileResult;
}
}
}
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<base href="@Url.Content("~/")" />
<link href="img/wnv.ico" rel="shortcut icon" />
<link href="styles/styles.css" type="text/css" rel="stylesheet">
<title>Display Session Variables</title>
</head>
<body>
<div>
<b style="font-size: 16px">The session variables</b><br />
<br />
<b>First Name:</b> <span id="firstNameLabel">@(ViewData["firstName"] != null ? ViewData["firstName"].ToString() : String.Empty)</span><br />
<b>Last Name:</b> <span id="lastNameLabel">@(ViewData["lastName"] != null ? ViewData["lastName"].ToString() : String.Empty)</span><br />
<b>Gender:</b> <span id="genderLabel">@(ViewData["gender"] != null && ViewData["gender"].ToString() == "maleRadioButton" ? "Male" : "Female")</span><br />
<b>I have a car:</b> <span id="haveCarLabel">@(ViewData["haveCar"] != null && ViewData["haveCar"].ToString() != "false" ? "Yes" : "No")</span><br />
<div id="carTypePanel" style="display : @(ViewData["haveCar"] != null && ViewData["haveCar"].ToString() == "false" ? "none" : "inline")">
<b>Car Type:</b> <span id="carTypeLabel">@(ViewData["carType"] != null ? ViewData["carType"].ToString() : String.Empty)</span><br />
</div>
<b>Comments:</b> <span id="commentsLabel">@(ViewData["comments"] != null ? ViewData["comments"].ToString() : String.Empty)</span><br />
</div>
</body>
</html>