You can convert only selected parts of an HTML page to PDF by specifying a CSS selector. This allows you to choose exactly which content is included in the PDF and to either remove or simply hide the unselected elements.
The CSS selector can be assigned to the HtmlToPdfConvertedElementsSelector property of the converter. For example, you can select an HTML element by its ID using the #ConvertedHtmlElementID selector, or select elements with a specific CSS class using the .ConvertedHtmlElementClass selector.
Furthermore, you can use the HtmlToPdfRemoveUnselectedElements property of the converter to specify what happens to the unselected elements. By default, this property is set to true, and the unselected elements are removed from the layout, allowing the content to reflow without them. If you set this property to false, the unselected elements are simply hidden and the space they originally occupied in the HTML page remains reserved in the content layout.
When you convert only a part of the HTML page, the content is reduced when the unselected elements are removed. By default, the converter renders a number of PDF pages containing the selected content, but some white space may remain on the last page. You can use the PdfDocumentControlAutoResizePdfPageHeight property to create a single PDF page that displays the converted elements. This property must be used in conjunction with the HtmlToPdfBrowserHeight property, which must be set to the minimum value of 1 pixel. An object of type PdfDocumentControl is accessible through the HtmlToPdfDocument property.
using System;
using System.IO;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using HiQPdf_Next_AspNetDemo.Models;
using HiQPdf.Next;
namespace HiQPdf_Next_AspNetDemo.Controllers
{
public class SelectHtmlElementsToConvertToPdfController : Controller
{
private readonly IWebHostEnvironment m_hostingEnvironment;
public SelectHtmlElementsToConvertToPdfController(IWebHostEnvironment hostingEnvironment)
{
m_hostingEnvironment = hostingEnvironment;
}
public ActionResult Index()
{
var model = SetViewModel();
return View(model);
}
[HttpPost]
public ActionResult ConvertHtmlToPdf(SelectHtmlElementsToConvertToPdfViewModel model)
{
if (!ModelState.IsValid)
{
var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
throw new ValidationException(errorMessage);
}
// Replace the demo serial number with the serial number received upon purchase
// to run the converter in licensed mode
Licensing.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";
// Create a HTML to PDF converter object with default settings
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
bool enableElementsSelector = model.EnableElementsSelector;
if (enableElementsSelector)
{
// The CSS selector used to identify the elements to include in the PDF
htmlToPdfConverter.ConvertedElementsSelector = model.ConvertedElementsSelector;
// Specify whether elements that are not matched by ConvertedElementsSelector
// should be completely removed from the layout rather than just hidden
htmlToPdfConverter.RemoveUnselectedElements = model.RemoveUnselectedElements;
// Automatically resizes the PDF page height to match the selected HTML content height
htmlToPdfConverter.Document.AutoResizePdfPageHeight = model.AutoResizePdfPageHeight;
if (htmlToPdfConverter.Document.AutoResizePdfPageHeight)
htmlToPdfConverter.BrowserHeight = 1;
}
byte[] outPdfBuffer = null;
if (model.HtmlPageSource == "Html")
{
string htmlWithForm = model.HtmlString;
string baseUrl = model.BaseUrl;
// Convert a HTML string to a PDF document
outPdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlWithForm, baseUrl);
}
else
{
string url = model.Url;
// Convert the HTML page to a PDF document
outPdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(url);
}
// Send the PDF file to browser
FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
fileResult.FileDownloadName = "SelectHtmlElementsToConvertToPdf.pdf";
return fileResult;
}
private SelectHtmlElementsToConvertToPdfViewModel SetViewModel()
{
var model = new SelectHtmlElementsToConvertToPdfViewModel();
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 - "SelectHtmlElementsToConvertToPdf".Length);
model.HtmlString = System.IO.File.ReadAllText(Path.Combine(contentRootPath, "DemoFiles/Html/Partially_Converterted.html"));
model.BaseUrl = rootUrl + "DemoFiles/Html/";
model.Url = rootUrl + "DemoFiles/Html/Partially_Converterted.html";
return model;
}
}
}