This quick and short tutorial assists on how to convert HTML to JPG in C# with the help of a few lines of code. It provides all the necessary details to configure the environment to accomplish this task along with the runnable C# code. To convert HTML to JPG C# code contains a very simple approach where the source HTML file is loaded and saved as multiple JPG files based on the contents size of the HTML file.
Steps to Convert HTML to JPG in C#
- Add a reference to Aspose.HTML to the project using the NuGet package manager to convert HTML to JPG
- Load the source HTML file from disk using the HTMLDocument class instance to convert it to JPG
- For customization of the output JPG image, instantiate the ImageSaveOptions class object
- Set the format of the output image as Jpeg
- Convert the entire HTML page to multiple images using Converter.ConvertHTML function
These steps describe the process by sharing the resources for configuring the application environment where using C# HTML to JPG conversion can be performed. The process is quite simple as just loading the HTML file is required along with the setting of the output images format. In the final step, the conversion is performed using the Converter class function ConvertHTML().
Code to Convert HTML to JPG in C#
using Aspose.Html; | |
using Aspose.Html.Converters; | |
using Aspose.Html.Rendering.Image; | |
using Aspose.Html.Saving; | |
namespace KBHtml | |
{ | |
class Program | |
{ | |
static void Main(string[] args) // Main function to convert HTML to JPG in C# | |
{ | |
// Remove the watermark in output JPG image by adding license | |
License licHtmlToJpg = new License(); | |
licHtmlToJpg.SetLicense(@"Aspose.Html.lic"); | |
// Load the source HTML document that is to be converted to images | |
HTMLDocument document = new HTMLDocument("SourceHtmlFile.html"); | |
// Initialize ImageSaveOptions to set output images parameters | |
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg); | |
// Convert HTML to JPG by rendering HTML to multiple images | |
Converter.ConvertHTML(document, options, "OutputJpegImage.jpg"); | |
System.Console.WriteLine("Done"); | |
} | |
} | |
} |
In order to convert HTML to JPG C# code imports all the necessary classes in the beginning that are required by the application. You can control the conversion process by using the ImageSaveOptions class that contains a number of properties that can be set like if you have CSS in your source HTML file, use the CSS property for configuration, use Text property to configure the rendered text quality, set background color, set output image resolution, and page setup.
This tutorial has taught us how to convert HTML to JPG in C#. For learning other types of conversions like HTML to PDF refer to the article on how to convert HTML page to PDF in C#.