Environment Configuration – C#

It is often helpful to have different configurations based on the environment where the application is running. For example, you may wish to configure the scripts policy, override document style applying a custom user stylesheet, or handle any web requests from the application. Aspose.HTML provides the Configuration class that can be used exactly for these purposes.

Sandboxing

A sandboxing flag set is a set of zero or more of the flags, which are used to restrict the abilities that potentially untrusted resources. The sandbox attribute allows you to set a number of restrictions on the content loaded in the frame, for example, block forms and scripts. This improves the security of the current document, especially when a document is loaded into the frame from an unverified source.

The following example demonstrates how to mark ‘Scripts’ as an untrusted resource. As a result, ‘Scripts’ will be disabled during the application execution.

 1using System.IO;
 2using Aspose.Html;
 3using Aspose.Html.Converters;
 4using Aspose.Html.Saving;
 5...
 6    // Prepare HTML code and save it to a file
 7    var code = "<span>Hello World!!</span> " +
 8               "<script>document.write('Have a nice day!');</script>";
 9
10    File.WriteAllText(Path.Combine(OutputDir, "sandboxing.html"), code);
11
12    // Create an instance of Configuration
13    using (var configuration = new Configuration())
14    {
15        // Mark 'scripts' as an untrusted resource
16        configuration.Security |= Sandbox.Scripts;
17
18        // Initialize an HTML document with specified configuration
19        using (var document = new HTMLDocument(Path.Combine(OutputDir, "sandboxing.html"), configuration))
20        {
21            // Convert HTML to PDF
22            Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "sandboxing_out.pdf"));
23        }
24    }

Services

All important functional is grouped into separated services for usability purpose and located into Aspose.Html.Services namespace.

User Agent Service

The User Agent Service allows you to specify a custom user stylesheet, a primary character set for the document, language and fonts settings. You can specify your custom style information for a particular document and provide as little or as much environment configuration changes as needed. The IUserAgentService interface describes a user agent environment.

User Style Sheet

The user is able to specify a custom style information for a particular document. This information applies to the document according to the cascading rules and may affect the presentation of the document. The next code snippet shows how to use the UserStyleSheet property:

 1using System.IO;
 2using Aspose.Html;
 3using Aspose.Html.Converters;
 4using Aspose.Html.Saving;
 5using Aspose.Html.Services;
 6...
 7    // Prepare HTML code and save it to a file
 8    var code = "<h1>User Agent Service </h1>\r\n" +
 9               "<p>The User Agent Service allows you to specify a custom user stylesheet, a primary character set for the document, language and fonts settings.</p>\r\n";
10
11    File.WriteAllText(Path.Combine(OutputDir, "user-agent-stylesheet.html"), code);
12
13    // Create an instance of Configuration
14    using (var configuration = new Configuration())
15    {
16        // Get the IUserAgentService
17        var userAgentService = configuration.GetService<IUserAgentService>();
18
19        // Set the custom style parameters for the "h1" and "p" elements
20        userAgentService.UserStyleSheet = "h1 { color:#a52a2a;; font-size:2em;}\r\n" +
21                                          "p { background-color:GhostWhite; color:SlateGrey; font-size:1.2em; }\r\n";
22
23        // Initialize the HTML document with specified configuration
24        using (var document = new HTMLDocument(Path.Combine(OutputDir, "user-agent-stylesheet.html"), configuration))
25        {
26            // Convert HTML to PDF
27            Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "user-agent-stylesheet_out.pdf"));
28        }
29    }

Character Set

The CharSet property sets the primary character-set for a document. In order to parse and display an HTML document correctly, the application must know what character-set (encoding) is used for the document. If the character encoding is not directly specified in the header of the document, Aspose.HTML uses UTF-8, which is defined as the default for HTML5 specification. However, if you are sure that your HTML document is written using different from UTF-8 encoding, you can specify it manually, as it follows.

 1using System.IO;
 2using Aspose.Html;
 3using Aspose.Html.Converters;
 4using Aspose.Html.Saving;
 5using Aspose.Html.Services;
 6...
 7    // Prepare HTML code and save it to a file
 8    var code = "<h1>Character Set</h1>\r\n" +
 9               "<p>The <b>CharSet</b> property sets the primary character-set for a document.</p>\r\n";
10
11    File.WriteAllText(Path.Combine(OutputDir, "user-agent-charset.html"), code);
12
13    // Create an instance of Configuration
14    using (var configuration = new Configuration())
15    {
16        // Get the IUserAgentService
17        var userAgentService = configuration.GetService<IUserAgentService>();
18
19        // Set the custom style parameters for the "h1" and "p" elements
20        userAgentService.UserStyleSheet = "h1 { color:salmon; }\r\n" +
21                                          "p { background-color: #f0f0f0; color:DarkCyan; font-size:1.2em; }\r\n";
22
23        // Set ISO-8859-1 encoding to parse the document
24        userAgentService.CharSet = "ISO-8859-1";
25
26        // Initialize the HTML document with specified configuration
27        using (var document = new HTMLDocument(Path.Combine(OutputDir, "user-agent-charset.html"), configuration))
28        {
29            // Convert HTML to PDF
30            Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "user-agent-charset_out.pdf"));
31        }
32    }

In the example above, we have used CharSet and UserStyleSheet properties for a setting of ISO-8859-1 encoding and a user style.

Install Font Folder

Aspose.HTML is a powerful library for working with HTML documents in .NET applications. It provides a wide range of features to enable developers to render HTML documents to various output formats, such as PDF, XPS, DOCX, and images. One of the key features of Aspose.HTML is its ability to work with custom fonts, enabling developers to add their own fonts to the rendering process.

The FontsSettings property is used for configuration of fonts handling. For a situation when you need to use the custom fonts instead of the fonts installed on OS, you can set the path to your custom folder, as it is shown in the following code snippet:

 1using System.IO;
 2using Aspose.Html;
 3using Aspose.Html.Converters;
 4using Aspose.Html.Saving;
 5using Aspose.Html.Services;
 6...
 7    // Prepare HTML code and save it to a file
 8    var code = "<h1>FontsSettings property</h1>\r\n" +
 9               "<p>The FontsSettings property is used for configuration of fonts handling.</p>\r\n";
10
11    File.WriteAllText(Path.Combine(OutputDir, "user-agent-fontsetting.html"), code);
12
13    // Create an instance of Configuration
14    using (var configuration = new Configuration())
15    {
16        // Get the IUserAgentService
17        var userAgentService = configuration.GetService<IUserAgentService>();
18
19        // Set the custom style parameters for the "h1" and "p" elements
20        userAgentService.UserStyleSheet = "h1 { color:#a52a2a; }\r\n" +
21                                          "p { color:grey; }\r\n";
22
23        // Set custom font folder path
24        userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir + "fonts"));
25
26        // Initialize the HTML document with specified configuration
27        using (var document = new HTMLDocument(Path.Combine(OutputDir, "user-agent-fontsetting.html"), configuration))
28        {
29            // Convert HTML to PDF
30            Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "user-agent-fontsetting_out.pdf"));
31        }
32    }

To set font folder using Aspose.HTML for .NET library, we use the SetFontsLookupFolder() method of the FontsSettings class. This method allows you to specify the folder where custom fonts are located. By setting the font folder, Aspose.HTML will look for fonts in the specified folder when rendering the HTML document.

The figure illustrates the result of the FontsSettings and UserStyleSheet properties applying (b) to the source “user-agent-fontsetting.html” file (a).

Text “FontsSettings property”

Runtime Service

This service gives you control over the lifetime of the internal processes. For instance, using IRuntimeService you can specify timeouts for JavaScripts. It is important to have such a timeout in case if a script contains an endless loop. The next code snippet demonstrates how to use timeouts.

 1using System.IO;
 2using Aspose.Html;
 3using Aspose.Html.Converters;
 4using Aspose.Html.Saving;
 5using Aspose.Html.Services;
 6...
 7    // Prepare HTML code and save it to a file
 8    var code = "<h1>Runtime Service</h1>\r\n" +
 9               "<script> while(true) {} </script>\r\n" +
10               "<p>The Runtime Service optimizes your system by helping it start apps and programs faster.</p>\r\n";
11
12    File.WriteAllText(Path.Combine(OutputDir, "runtime-service.html"), code);
13
14    // Create an instance of Configuration
15    using (var configuration = new Configuration())
16    {
17        // Limit JS execution time to 5 seconds
18        var runtimeService = configuration.GetService<IRuntimeService>();
19        runtimeService.JavaScriptTimeout = TimeSpan.FromSeconds(5);
20
21        // Initialize an HTML document with specified configuration
22        using (var document = new HTMLDocument(Path.Combine(OutputDir, "runtime-service.html"), configuration))
23        {
24            // Convert HTML to PNG
25            Converter.ConvertHTML(document, new ImageSaveOptions(), Path.Combine(OutputDir, "runtime-service_out.png"));
26        }
27    }

Network Service

Aspose.HTML for .Net offers the INetworkService that allows you to control all incoming/outcoming traffic and implement your custom message handlers. It can be used for different purposes, such as: create custom caching mechanism, trace/logging request messages, etc.

Message Handlers

The following example demonstrates how to create a custom message handler – LogMessageHandler – to log information about unreachable resources:

 1using System.IO;
 2using Aspose.Html;
 3using System.Net;
 4using Aspose.Html.Net;
 5using System.Collections.Generic;
 6...
 7    // This message handler logs all failed requests to the console
 8	private class LogMessageHandler : MessageHandler
 9    {
10        public List<string> ErrorMessages
11        {
12            get { return errors; }
13        }
14        public override void Invoke(INetworkOperationContext context)
15        {
16            // Check whether response is OK
17            if (context.Response.StatusCode != HttpStatusCode.OK)
18            {
19                // Set error information
20                errors.Add(string.Format("File '{0}' Not Found", context.Request.RequestUri));
21            }
22
23            // Invoke the next message handler in the chain
24            Next(context);
25        }
26    }

The next code snippet demonstrates how to use the LogMessageHandler class created in the previous example to log information about unavailable resources.

 1using System;
 2using System.IO;
 3using Aspose.Html;
 4using Aspose.Html.Converters;
 5using Aspose.Html.Net;
 6using Aspose.Html.Saving;
 7using Aspose.Html.Services;
 8...
 9    // Prepare HTML code and save it to a file
10    var code = "<img src=\"https://docs.aspose.com/svg/net/drawing-basics/filters-and-gradients/park.jpg\" >\r\n" +
11               "<img src=\"https://docs.aspose.com/html/net/missing1.jpg\" >\r\n" +
12			   "<img src=\"https://docs.aspose.com/html/net/missing2.jpg\" >\r\n";
13
14    File.WriteAllText(Path.Combine(OutputDir, "network-service.html"), code);
15
16    // Create an instance of Configuration
17    using (var configuration = new Configuration())
18    {
19        // Add the LogMessageHandler to the chain of existing message handlers
20        var networkService = configuration.GetService<INetworkService>();
21
22        var logHandler = new LogMessageHandler();
23        networkService.MessageHandlers.Add(logHandler);
24
25        // Initialize an HTML document with specified configuration
26        using (var document = new HTMLDocument(Path.Combine(OutputDir, "network-service.html"), configuration))
27        {
28            //Convert HTML to PNG
29            Converter.ConvertHTML(document, new ImageSaveOptions(), Path.Combine(OutputDir, "network-service_out.png"));
30
31            // Print the List of ErrorMessages
32            foreach (string errorMessage in logHandler.ErrorMessages)
33            {
34                Console.WriteLine(errorMessage);
35            }
36        }
37    }

After the example run:

File 'https://docs.aspose.com/html/net/missing1.jpg' Not Found
File 'https://docs.aspose.com/html/net/missing2.jpg' Not Found

You can download the complete examples and data files from GitHub.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.