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 for .NET 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.

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

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:

 1// Prepare HTML code and save it to a file
 2var code = "<h1>User Agent Service </h1>\r\n" +
 3           "<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";
 4           
 5File.WriteAllText(Path.Combine(OutputDir, "user-agent-stylesheet.html"), code);
 6
 7// Create an instance of Configuration
 8using (var configuration = new Configuration())
 9{
10    // Get the IUserAgentService
11    var userAgentService = configuration.GetService<IUserAgentService>();
12
13    // Set the custom style parameters for the <h1> and <p> elements
14    userAgentService.UserStyleSheet = "h1 { color:#a52a2a;; font-size:2em;}\r\n" +
15                                      "p { background-color:GhostWhite; color:SlateGrey; font-size:1.2em; }\r\n";
16                    
17    // Initialize the HTML document with specified configuration
18    using (var document = new HTMLDocument(Path.Combine(OutputDir, "user-agent-stylesheet.html"), configuration))
19    {                   
20        // Convert HTML to PDF
21        Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "user-agent-stylesheet_out.pdf"));
22    }
23}

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 for .NET 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.

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

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 for .NET 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:

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

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.

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

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:

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

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

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

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.