Convert HTML to JPG in C#
JPG files can contain high-quality image data with lossless compression. This unique compression feature allows to quickly and efficiently share JPG images and use them widely on the Web, computers, and mobile devices. Converting HTML files to the JPG image may be required, for example, if you want to add a web page in a PowerPoint presentation or send it by e-mail. Using Converter.ConvertHTML methods is the most common way to convert HTML code into various formats. JPG is a commonly used format for storing images, and HTML to JPG conversion is very popular. With Aspose.HTML for .NET, you can convert HTML to JPG format programmatically with full control over a wide range of conversion parameters.
In this article, you find information on converting HTML to JPG by using ConvertHTML() methods of the Converter class and applying ImageSaveOptions and ICreateStreamProvider parameters.
Online HTML Converter
You can check the Aspose.HTML for .NET API functionality and convert HTML in real-time. Please load HTML from the local file system, select the output format and run the example. In the example, the save options are set by default. You will immediately receive the result as a separate file.
If you want to convert HTML to JPG programmatically, please see the following C# code examples.
HTML to JPG by a single line of code
The static methods of the Converter class are primarily used as the easiest way to convert HTML code into various formats. You can convert HTML to JPG in your C# application literally with a single line of code!
1// Invoke the ConvertHTML() method to convert the HTML code to JPG image
2Converter.ConvertHTML(@"<h1>Convert HTML to JPG!</h1>", ".", new ImageSaveOptions(ImageFormat.Jpeg), Path.Combine(OutputDir, "convert-with-single-line.jpg"));
Convert HTML to JPG
Converting a file to another format using the ConvertHTML() method is a sequence of operations among which document loading and saving:
- Load an HTML file using the HTMLDocument class ( spring.html).
- Create a new
ImageSaveOptions object with
ImageFormat.Jpeg
. By default, the Format property is PNG. - Use the ConvertHTML() method of the Converter class to save HTML as a JPG image. You need to pass the HTMLDocument, ImageSaveOptions, and output file path to the ConvertHTML() method to convert HTML to JPG.
Please take a look over the following C# code snippet which shows the process of converting HTML to JPG using Aspose.HTML for .NET.
1// Prepare a path to a source HTML file
2string documentPath = Path.Combine(DataDir, "spring.html");
3
4// Prepare a path to save the converted file
5string savePath = Path.Combine(OutputDir, "spring-output.jpg");
6
7// Initialize an HTML document from the file
8using var document = new HTMLDocument(documentPath);
9
10// Create an instance of the ImageSaveOptions class
11var options = new ImageSaveOptions(ImageFormat.Jpeg);
12
13// Convert HTML to JPG
14Converter.ConvertHTML(document, options, savePath);
The figure illustrates the spring-output.jpg file.
You can download the complete examples and data files from GitHub.
Save Options
The JPG images creation functionality can be enhanced with save options per your needs. Aspose.HTML for .NET allows converting HTML to JPG using default or custom save options. ImageSaveOptions usage enables you to customize the rendering process. You can specify the image format, page size, margins, CSS media-type, etc.
Property | Description |
---|---|
Compression | Sets Tagged Image File Format (TIFF) Compression. By default, this property is LZW. |
CSS | Gets a CssOptions object which is used for configuration of CSS properties processing. |
Format | Sets the ImageFormat (JPG, PNG, BMP, TIFF, or GIF). By default, this property is PNG. |
BackgroundColor | This property sets the color that will fill the background. By default, this property is Transparent. |
PageSetup | This property gets a page setup object and uses it for configuration output page-set. |
HorizontalResolution | Sets horizontal resolution for output images in pixels per inch. The default value is 300 dpi. |
VerticalResolution | Sets vertical resolution for output images in pixels per inch. The default value is 300 dpi. |
UseAntialiasing | This property sets the image rendering quality. Antialiasing is enabled by default. |
Text | Gets a TextOptions object which is used for configuration of text rendering. |
The following example shows how to use ImageSaveOptions and create the output image with custom save options such as a page size and background color:
1string documentPath = Path.Combine(OutputDir, "save-options.html");
2string savePath = Path.Combine(OutputDir, "save-options-output.jpg");
3
4// Prepare HTML code and save it to a file
5var code = "<h1> Image SaveOptions </h1>\r\n" +
6 "<p>Using ImageSaveOptions Class, you can programmatically apply a wide range of conversion parameters such as BackgroundColor, Format, Compression, PageSetup, etc.</p>\r\n";
7
8File.WriteAllText(documentPath, code);
9
10// Initialize an HTML Document from the html file
11using var document = new HTMLDocument(documentPath);
12
13// Set up the page-size 500x250 pixels, margins and change the background color to AntiqueWhite
14var options = new ImageSaveOptions(ImageFormat.Jpeg)
15{
16 BackgroundColor = System.Drawing.Color.AntiqueWhite
17};
18options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(500, 250), new Margin(40, 40, 20, 20));
19
20// Convert HTML to JPG
21Converter.ConvertHTML(document, options, savePath);
To learn more about the ImageSaveOptions class, please read the Fine-Tuning Converters article.
Convert HTML to JPG using ImageSaveOptions
To convert HTML to JPG with ImageSaveOptions specifying, you should follow a few steps:
- Load an HTML file using one of the HTMLDocument() constructors of the HTMLDocument class ( color.html).
- Create a new ImageSaveOptions object with JPG ImageFormat and specify save options. By default, the Format property is PNG.
- Use the ConvertHTML() method of the Converter class to save HTML as a JPG image. You need to pass the HTMLDocument, ImageSaveOptions, and output file path to the ConvertHTML() method to convert HTML to JPG.
The following C# code snippet shows how to convert HTML to JPG using custom save options:
1// Prepare a path to a source HTML file
2string documentPath = Path.Combine(DataDir, "color.html");
3
4// Prepare a path to save the converted file
5string savePath = Path.Combine(OutputDir, "color-output-options.jpg");
6
7// Initialize an HTML document from the file
8using var document = new HTMLDocument(documentPath);
9
10// Initialize ImageSaveOptions
11var options = new ImageSaveOptions(ImageFormat.Jpeg)
12{
13 UseAntialiasing = true,
14 HorizontalResolution = 200,
15 VerticalResolution = 200,
16 BackgroundColor = System.Drawing.Color.AliceBlue
17};
18options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(500, 500), new Margin(30, 20, 10, 10));
19
20// Convert HTML to JPG
21Converter.ConvertHTML(document, options, savePath);
The
ImageSaveOptions() constructor initializes an instance of the ImageSaveOptions class that is passed to ConvertHTML() method. The ConvertHTML() method takes the document
, options
, output file path savePath
and performs the conversion operation.
In the above example, we use:
BackgroundColor
property that sets the color that will fill the background. The default BackgroundColor is Transparent.- Horizon
talResolution and
VerticalResolution` properties that set horizontal/vertical resolution for output images in pixels per inch. By default, these properties are 300 dpi. UseAntialiasing
property that sets the rendering quality for this image. This example usesUseAntialiasing = true
for quality rendering.PageSetup
property that specifies the page size and margins in pixels.
Use UseAntialiasing = true
when you want to improve the visual quality of rendered shapes, text, and images in your application, especially when clarity and smooth edges are essential. Enabling antialiasing smooths out jagged edges by blending the colors of pixels around the edges, resulting in a softer, more refined look.
While UseAntialiasing = true
provides better visual quality, it can also increase processing time. For applications where rendering speed is a priority, it may be optimal to set UseAntialiasing = false
.
The figure illustrates the color-output-options.jpg file.
Output Stream Providers
If it is required to save files in the remote storage (e.g., cloud, database, etc.) you can implement the ICreateStreamProvider interface to have manual control over the file creating process. This interface is designed as a callback object to create a stream at the beginning of the document/page (depending on the output format) and release the early created stream after rendering the document/page.
Aspose.HTML for .NET provides various types of output formats for rendering operations. Some of these formats produce a single output file (for instance, PDF, XPS), others create multiple files (Image formats – JPG, PNG, etc.).
The example below shows how to implement and use your own MemoryStreamProvider in the application:
1class MemoryStreamProvider : Aspose.Html.IO.ICreateStreamProvider
2{
3 // List of MemoryStream objects created during the document rendering
4 public List<MemoryStream> Streams { get; } = new List<MemoryStream>();
5
6 public Stream GetStream(string name, string extension)
7 {
8 // This method is called when only one output stream is required, for instance for XPS, PDF or TIFF formats
9 MemoryStream result = new MemoryStream();
10 Streams.Add(result);
11 return result;
12 }
13
14 public Stream GetStream(string name, string extension, int page)
15 {
16 // This method is called when the creation of multiple output streams are required. For instance, during the rendering HTML to list of image files (JPG, PNG, etc.)
17 MemoryStream result = new MemoryStream();
18 Streams.Add(result);
19 return result;
20 }
21
22 public void ReleaseStream(Stream stream)
23 {
24 // Here you can release the stream filled with data and, for instance, flush it to the hard-drive
25 }
26
27 public void Dispose()
28 {
29 // Releasing resources
30 foreach (var stream in Streams)
31 stream.Dispose();
32 }
33}
The following code snippet demonstrates how to convert an HTML file to a JPG file using a memory stream.
1// Create an instance of MemoryStreamProvider
2using var streamProvider = new MemoryStreamProvider();
3
4// Initialize an HTML document
5using var document = new HTMLDocument(@"<h1>Convert HTML to JPG File Format!</h1>", ".");
6
7// Convert HTML to JPG using the MemoryStreamProvider
8Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider);
9
10// Get access to the memory stream that contains the result data
11var memory = streamProvider.Streams.First();
12memory.Seek(0, SeekOrigin.Begin);
13
14// Flush the result data to the output file
15using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.jpg")))
16{
17 memory.CopyTo(fs);
18}
You can download the complete examples and data files from GitHub.
Download the Aspose.HTML for .NET library, which allows you to successfully, quickly, and easily convert your HTML, MHTML, EPUB, SVG, and Markdown documents to the most popular formats.
Aspose.HTML offers a free online HTML to JPG Converter that converts HTML to JPG image with high quality, easy and fast. Just upload, convert your files and get results in a few seconds!