HTML to Image Converter Overview

Winnovative PDF Next for .NET also allows you to easily convert HTML pages and HTML strings to raster images in PNG, JPG or WebP format with just a few lines of code. In this section you can learn about the basic settings of the converter.

The HTML to Image functionality is part of the HTML to PDF Converter component of the Winnovative PDF Next for .NET library.

This component is bundled and distributed as two separate NuGet packages for Windows and Linux, each including the same .NET Standard 2.0 library and different native runtimes. Targeting .NET Standard 2.0 makes the packages compatible with a wide range of .NET Core and .NET Framework versions.

You can reference the Winnovative.Pdf.Next.HtmlToPdf.Windows NuGet package in applications running on Windows or the Winnovative.Pdf.Next.HtmlToPdf.Linux NuGet package in applications running on Linux to enable HTML to PDF conversion in your application. The package for Windows is also referenced by the Winnovative.Pdf.Next.Windows metapackage, and the package for Linux is referenced by the Winnovative.Pdf.Next.Linux metapackage.

There are also multiplatform metapackages which reference both the Windows and Linux HTML to PDF packages: Winnovative.Pdf.Next.HtmlToPdf for the HTML to PDF functionality and Winnovative.Pdf.Next for the entire Winnovative PDF Next library.

Convert HTML to Image using the HtmlToImageConverter Class

You can use one of the HtmlToImageConverter class methods to convert a URL or an HTML string to an image in various formats.

The class is defined in the Core component of the library, but using it requires the Core runtime. The HTML to PDF NuGet packages described above correctly reference both the Core assembly and the Core runtime in your application.

The resulting image can be:

Asynchronous HTML to Image Methods

There are also asynchronous variants of these methods that follow the Task-based Asynchronous Pattern (TAP) in .NET, allowing HTML to image conversion to run in parallel using async and await. These methods share the same names as their synchronous counterparts and include the "Async" suffix. They also accept an optional System.ThreadingCancellationToken parameter that can be used to cancel the conversion operation where applicable.

HTML to Image Converter Options

The basic options you can set are grouped into several categories.

HTML Viewer Options

  • HTML Viewer Width. This option is the equivalent in the converter of the browser window width. The property you can set in your code to control the browser window width is HtmlToImageConverterHtmlViewerWidth.

  • HTML Viewer Height. This option is the equivalent in the converter of the browser window height and represents the height of the HTML viewer. By default, the HTML to Image Converter captures only the content in the viewport determined by the HTML Viewer Width and Height, but you can use the next option to go beyond the viewport and capture the entire HTML page. The property you can set in your code to control the browser window height is HtmlToImageConverterHtmlViewerHeight.

  • Capture Entire Page. The HtmlToImageConverterCaptureEntirePage property controls whether the entire HTML page will be captured or only the area defined by the HtmlViewerHeight property. The captured content is limited by the MaxHtmlViewerHeight property. By default, this property is set to true. Additionally, you can choose between the browser’s internal mechanism and a custom algorithm for capturing the full page using the HtmlToImageConverterCaptureEntirePageMode property. By default, the Browser mode is used.

Image Options

  • Image Format. This option allows you to select the output image format. You can choose between PNG, JPG and WebP. You can specify the image format as a parameter of the converter methods used to convert a URL or an HTML string.

Navigation Options

  • Navigation Timeout. This option represents the maximum time to wait for a web page to be loaded by the converter. If the page cannot be loaded within this time interval, the converter will throw an exception. The property you can set in your code for this option is HtmlToImageConverterNavigationTimeout.

  • Delay Conversion. This option represents an additional time to wait after the HTML page has finished loading, allowing asynchronous operations to complete before capturing the content. If you cannot estimate the additional time needed, you also have the option to manually trigger the conversion. The property you can set in your code for this option is HtmlToImageConverterConversionDelay.

Code Sample - Convert HTML to Image

C#
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using Winnovative_Next_AspNetDemo.Models;
using Winnovative_Next_AspNetDemo.Models.HTML_to_Image;

// Use Winnovative Namespace
using Winnovative.Pdf.Next;

namespace Winnovative_Next_AspNetDemo.Controllers.HTML_to_Image
{
    public class Convert_HTML_to_ImageController : Controller
    {
        [HttpPost]
        public ActionResult ConvertHtmlToImage(Convert_HTML_to_Image_ViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
                throw new ValidationException(errorMessage);
            }

            // Set license key received after purchase to use the converter in licensed mode
            // Leave it not set to use the library in demo mode
            Licensing.LicenseKey = "3FJDU0ZDU0NTQkddQ1NAQl1CQV1KSkpKU0M=";

            // Create a HTML to Image converter object with default settings
            HtmlToImageConverter htmlToImageConverter = new HtmlToImageConverter();

            // Set HTML Viewer width in pixels which is the equivalent in converter of the browser window width
            htmlToImageConverter.HtmlViewerWidth = model.HtmlViewerWidth;

            // Set HTML viewer height in pixels to convert the top part of a HTML page 
            // Leave it not set to convert the entire HTML
            if (model.HtmlViewerHeight.HasValue)
                htmlToImageConverter.HtmlViewerHeight = model.HtmlViewerHeight.Value;

            // enable the conversion of the entire page, not only the viewport defined by HtmlViewerWidth and HtmlViewerHeight
            htmlToImageConverter.CaptureEntirePage = model.CaptureEntirePage;

            // Set the loading mode used to capture the entire page content
            htmlToImageConverter.CaptureEntirePageMode = model.CaptureEntirePageMode == "Browser" ?
                CaptureEntirePageMode.Browser : CaptureEntirePageMode.Custom;

            // Optionally auto resize HTML viewer height at the HTML content size determined after the initial loading
            htmlToImageConverter.AutoResizeHtmlViewerHeight = model.AutoResizeViewerHeight;

            // Set the maximum time in seconds to wait for HTML page to be loaded 
            // Leave it not set for a default 120 seconds maximum wait time
            htmlToImageConverter.NavigationTimeout = model.NavigationTimeout;

            // 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
            if (model.ConversionDelay.HasValue)
                htmlToImageConverter.ConversionDelay = model.ConversionDelay.Value;

            byte[] outImageBuffer = null;
            if (model.HtmlPageSource == "Url")
            {
                string url = model.Url;

                // Convert the HTML page given by an URL to an image into a memory buffer
                outImageBuffer = htmlToImageConverter.ConvertUrl(url, SelectedImageFormat(model.ImageFormat));
            }
            else
            {
                string htmlString = model.HtmlString;
                string baseUrl = model.BaseUrl;

                // Convert a HTML string with a base URL to an image into a memory buffer
                outImageBuffer = htmlToImageConverter.ConvertHtml(htmlString ?? string.Empty, baseUrl, SelectedImageFormat(model.ImageFormat));
            }

            string imageFormatName = model.ImageFormat.ToLower();

            // Send the image file to browser
            FileResult fileResult = new FileContentResult(outImageBuffer, "image/" + (imageFormatName == "jpg" ? "jpeg" : imageFormatName));
            fileResult.FileDownloadName = "HTML_to_Image." + imageFormatName;

            return fileResult;
        }

        private ImageType SelectedImageFormat(string selectedValue)
        {
            switch (selectedValue)
            {
                case "Png":
                    return ImageType.Png;
                case "Jpg":
                    return ImageType.Jpeg;
                case "Webp":
                    return ImageType.Webp;
                default:
                    return ImageType.Png;
            }
        }
    }
}

See Also