The HiQPdf HTML to PDF and HTML to Image converters can be configured to transmit a set of HTTP cookies to the web server when requesting the web page to be converted. For example, the HTTP cookies to be transmitted to the web server are added to the HttpCookies collection of the HiQPdf.Next.HtmlToPdf object using the KeyValueCollectionAdd(String, String) method, which takes the cookie name and cookie value as parameters. Adding custom HTTP cookies to a request can be useful for scenarios such as handling various types of authentication. Below is a simple code sample that demonstrates how to add cookies to a request.
A valid cookie name and a RFC 6265-encoded value must be provided.
Set HTTP Cookies Demo
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using HiQPdf_Next_AspNetDemo.Models;
using HiQPdf.Next;
namespace HiQPdf_Next_AspNetDemo.Controllers
{
public class CookiesController : Controller
{
public IActionResult Index()
{
var model = new CookiesViewModel();
return View(model);
}
[HttpPost]
public ActionResult ConvertToPdf(CookiesViewModel model)
{
if (!ModelState.IsValid)
{
var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
throw new ValidationException(errorMessage);
}
// Set the serial number received after purchase to use the library in licensed mode; leave it commented for demo mode
// Licensing.SerialNumber = "your-serial-number";
// Create an HTML to PDF converter object with default settings
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
// Set HTTP request cookies
// The caller must provide a valid cookie name and RFC 6265-encoded value
if (!string.IsNullOrEmpty(model.Cookie1Name) && !string.IsNullOrEmpty(model.Cookie1Value))
htmlToPdfConverter.HttpCookies.Add(model.Cookie1Name, model.Cookie1Value);
if (!string.IsNullOrEmpty(model.Cookie2Name) && !string.IsNullOrEmpty(model.Cookie2Value))
htmlToPdfConverter.HttpCookies.Add(model.Cookie2Name, model.Cookie2Value);
if (!string.IsNullOrEmpty(model.Cookie3Name) && !string.IsNullOrEmpty(model.Cookie3Value))
htmlToPdfConverter.HttpCookies.Add(model.Cookie3Name, model.Cookie3Value);
if (!string.IsNullOrEmpty(model.Cookie4Name) && !string.IsNullOrEmpty(model.Cookie4Value))
htmlToPdfConverter.HttpCookies.Add(model.Cookie4Name, model.Cookie4Value);
if (!string.IsNullOrEmpty(model.Cookie5Name) && !string.IsNullOrEmpty(model.Cookie5Value))
htmlToPdfConverter.HttpCookies.Add(model.Cookie5Name, model.Cookie5Value);
byte[] pdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(model.Url);
FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
fileResult.FileDownloadName = "HTTP_Request_Cookies.pdf";
return fileResult;
}
}
}