Convert HTML to PNG in C#
PNG is one of the most used image file formats. It supports lossless image compression that makes it popular among its users. Converting HTML files to the PNG image may be required, for example, if you want to add a web page in a PowerPoint presentation, insert it on a blog for your readers, or send by e-mail. With Aspose.HTML for .NET, you can convert HTML to PNG format programmatically with full control over a wide range of conversion parameters.
In this article, you find information on how to convert HTML to PNG by using ConvertHTML() methods of the Converter class, and how to apply ImageSaveOptions and ICreateStreamProvider parameters.
Online HTML Converter
You can check the Aspose.HTML 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 PNG programmatically, please see the following C# code examples.
HTML to PNG by a single line of code
The static methods of the Converter class are primarily used as the easiest way to convert an HTML code into various formats. You can convert HTML to PNG in your C# application literally with a single line of code!
1// Invoke the ConvertHTML() method to convert HTML to PNG
2Converter.ConvertHTML(@"<h1>Convert HTML to PNG!</h1>", ".", new ImageSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.png"));
Convert HTML to PNG
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.
- Create a new ImageSaveOptions object. By default, the Format property is PNG.
- Use the ConvertHTML() method of the Converter class to save HTML as a PNG image. You need to pass the HTMLDocument, ImageSaveOptions, and output file path to the ConvertHTML() method to convert HTML to PNG.
Please take a look over the following C# code snippet which shows the process of converting HTML to PNG using Aspose.HTML for .NET.
1// Prepare a path to a source HTML file
2string documentPath = Path.Combine(DataDir, "nature.html");
3
4// Prepare a path to save the converted file
5string savePath = Path.Combine(OutputDir, "nature-output.png");
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.Png);
12
13// Convert HTML to PNG
14Converter.ConvertHTML(document, options, savePath);
Save Options
Aspose.HTML allows converting HTML to PNG 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. |
To learn more about the ImageSaveOptions class, please read the Fine-Tuning Converters article.
Convert HTML to PNG using ImageSaveOptions
To convert HTML to PNG with ImageSaveOptions specifying, you should follow a few steps:
- Load an HTML file using one of the HTMLDocument() constructors of the HTMLDocument class.
- Create a new ImageSaveOptions object 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 PNG.
The following C# code snippet shows how to convert HTML to PNG using custom save options:
1// Prepare a path to a source HTML file
2string documentPath = Path.Combine(DataDir, "nature.html");
3
4// Prepare a path to save the converted file
5string savePath = Path.Combine(OutputDir, "nature-output-options.png");
6
7// Initialize an HTML document from the file
8using var document = new HTMLDocument(documentPath);
9
10// Initialize ImageSaveOptions
11var options = new ImageSaveOptions()
12{
13 UseAntialiasing = false,
14 HorizontalResolution = 100,
15 VerticalResolution = 100,
16 BackgroundColor = System.Drawing.Color.Beige
17};
18
19// Convert HTML to PNG
20Converter.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 add:
BackgroundColor
property that sets the color that will fill the background. The default BackgroundColor is Transparent.HorizontalResolution
andVerticalResolution
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 = false
for simpler, performance-oriented rendering that does not require antialiasing.
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
.
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 C# code demonstrates how to use the MemoryStreamProvider class and the Aspose.HTML for .NET library to convert HTML to PNG and save the result to a file.
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 PNG File Format!</h1>", ".");
6
7// Convert HTML to JPG using the MemoryStreamProvider
8Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Png), 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.png")))
16{
17 memory.CopyTo(fs);
18}
You can download the complete examples and data files from GitHub.
Aspose.HTML offers a free online HTML to PNG Converter that converts HTML to PNG image with high quality, easy and fast. Just upload, convert your files and get results in a few seconds!