Select HTML Elements to Convert to Image

You can convert only selected parts of an HTML page to an image by specifying a CSS selector. This allows you to choose exactly which content will be included in the image and to either remove or simply hide the unselected elements.

The CSS selector can be assigned to the HtmlToImageConvertedElementsSelector 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 HtmlToImageRemoveUnselectedElements 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 is still reserved in the content layout.

When you convert only a part of the HTML page, it is also recommended to set the HtmlToPdfBrowserHeight property to the minimum value of 1 pixel to obtain an image that matches the rendered content.

Code Sample - Select HTML Elements to Convert to Image

C#
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using HiQPdf.Chromium;

namespace HiQPdf_Chromium_AspNetDemo.Controllers
{
    public class Select_HTML_Elements_to_Convert_to_ImageController : Controller
    {
        private readonly IWebHostEnvironment m_hostingEnvironment;
        public Select_HTML_Elements_to_Convert_to_ImageController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

        public ActionResult Index()
        {
            SetCurrentViewData();

            return View();
        }

        [HttpPost]
        public ActionResult ConvertHtmlToImage(IFormCollection collection)
        {
            // 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 Image converter object with default settings    
            HtmlToImage htmlToImageConverter = new HtmlToImage();

            bool enableElementsSelector = collection["enableElementsSelectorCheckBox"].Count > 0;
            if (enableElementsSelector)
            {
                // The CSS selector used to identify the elements to include in the image
                htmlToImageConverter.ConvertedElementsSelector = collection["convertedElementsSelectorTextBox"];

                // Specify whether elements that are not matched by ConvertedElementsSelector
                // should be completely removed from the layout rather than just hidden
                htmlToImageConverter.RemoveUnselectedElements = collection["removeUnselectedElementsCheckBox"].Count > 0;

                // Allow image to auto-resize at minimum height
                htmlToImageConverter.BrowserHeight = 1;
            }

            byte[] outImageBuffer = null;

            if (collection["HtmlPageSource"] == "convertHtmlRadioButton")
            {
                string htmlWithForm = collection["htmlStringTextBox"];
                string baseUrl = collection["baseUrlTextBox"];

                // Convert a HTML string to a PNG image
                outImageBuffer = htmlToImageConverter.ConvertHtmlToMemory(htmlWithForm, baseUrl, ImageType.Png);
            }
            else
            {
                string url = collection["urlTextBox"];

                // Convert the HTML page to a PNG image
                outImageBuffer = htmlToImageConverter.ConvertUrlToMemory(url, ImageType.Png);
            }

            // Send the image file to browser
            FileResult fileResult = new FileContentResult(outImageBuffer, "image/png");
            fileResult.FileDownloadName = "Select_HTML_Elements_to_Convert_to_Image.png";

            return fileResult;
        }

        private void SetCurrentViewData()
        {
            ViewData["ContentRootPath"] = 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();

            ViewData["CurrentPageUrl"] = uriBuilder.Uri.AbsoluteUri;
        }
    }
}

See Also