Environment Configuration in C#

Use the Configuration class when an HTML workflow needs a controlled processing environment. You can configure sandbox flags, user agent settings, custom stylesheets, character encoding, font lookup folders, JavaScript runtime timeout, and network message handlers before creating an HTMLDocument.

Environment configuration is useful when the same HTML workflow must behave consistently across local machines, servers, Docker images, or restricted runtime environments. In Aspose.HTML for .NET, configuration is created first, services are adjusted through that configuration, and the configured object is passed to the HTMLDocument constructor.

This page is an overview of the main configuration services. For task-specific guides, use the deeper articles linked from each section: Sandboxing for security flags, How to Set Font Folder for rendering with custom fonts, and Message Handlers for advanced network request control.

Choose a Configuration Area

If you need toConfigure this
Disable scripts, images, forms, plugins, or navigationSandboxing with Configuration.Security and Sandbox flags.
Apply a user stylesheet to every rendered documentIUserAgentService.UserStyleSheet.
Specify the document encoding when it is not detected correctlyIUserAgentService.CharSet.
Use custom fonts for rendering and conversionIUserAgentService.FontsSettings.SetFontsLookupFolder().
Limit JavaScript execution timeIRuntimeService.JavaScriptTimeout.
Log, inspect, block, or customize network requestsINetworkService.MessageHandlers.

Sandboxing

Sandboxing controls selected document capabilities through Configuration.Security. Use it when a workflow should treat scripts, images, forms, plugins, navigation, or origin behavior as restricted before the document is loaded.

The dedicated Sandboxing article explains Sandbox flags and includes examples for disabling scripts and image loading. Keep sandbox-related implementation details there; this page treats sandboxing as one part of the broader configuration model.

User Agent Service

The IUserAgentService interface describes user-agent-level settings used while processing HTML. Use it to apply a user stylesheet, set a primary character set, and configure font lookup behavior for rendering.

User Style Sheet

A user stylesheet lets you apply CSS rules through configuration instead of modifying the source HTML. The rules participate in the CSS cascade and can affect rendered output such as PDF, XPS, DOCX, and images.

To apply a user stylesheet in C#:

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

Character Set

The CharSet property sets the primary character set for a document. If the document does not declare an encoding, Aspose.HTML for .NET uses UTF-8, the default encoding for HTML5. Set CharSet manually only when you know the source HTML uses another encoding and the encoding is not detected from the document itself.

To set the character set in C#:

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

Install Font Folder

Font configuration matters when HTML rendering depends on fonts that are not installed in the operating system or container image. Use FontsSettings and SetFontsLookupFolder() to point Aspose.HTML to a folder with custom fonts.

To configure a custom font folder in C#:

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

The figure compares rendering before and after applying FontsSettings and UserStyleSheet: (a) the source HTML rendered with default font settings; (b) the result after configuring a custom font folder and user stylesheet.

HTML rendering before and after applying FontsSettings in C#

For a deeper workflow, see How to Set Font Folder.

Runtime Service

The IRuntimeService interface controls runtime behavior for internal processing. A common use case is limiting JavaScript execution time so an endless or long-running script cannot block the workflow indefinitely.

The next example sets JavaScriptTimeout to five seconds before loading an HTML document that contains an endless loop.

To limit JavaScript execution time in C#:

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

If scripts should not run at all, use Sandboxing with Sandbox.Scripts instead of only setting a timeout.

Network Service

The INetworkService interface lets you control request and response processing through message handlers. Use it when you need request logging, caching, URL filtering, custom schemes, authentication, timeouts, or other network-layer behavior.

For a complete introduction to handler pipelines, see Message Handlers. The example below keeps a compact logging scenario inside this overview page.

Log Unavailable Resources

The first snippet defines a custom LogMessageHandler class that records failed resource requests. The handler checks the response status and stores a message when a requested resource cannot be loaded.

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

The next snippet adds LogMessageHandler to the INetworkService.MessageHandlers collection, loads HTML with several image URLs, converts it to PNG, and prints messages for unavailable resources.

To log unavailable resources in C#:

  1. Create a custom message handler by inheriting from MessageHandler.
  2. Override Invoke() and inspect context.Response.StatusCode.
  3. Get INetworkService from the configuration.
  4. Add the handler to networkService.MessageHandlers.
  5. Load and process the document with that configuration.
  6. Read or print the collected log messages after processing.
 1// Log network errors during HTML processing using custom message handler in C#
 2
 3// Prepare HTML code and save it to a file
 4string code = "<img src=\"https://docs.aspose.com/svg/net/drawing-basics/filters-and-gradients/park.jpg\" >\r\n" +
 5              "<img src=\"https://docs.aspose.com/html/net/missing1.jpg\" >\r\n" +
 6              "<img src=\"https://docs.aspose.com/html/net/missing2.jpg\" >\r\n";
 7
 8File.WriteAllText(Path.Combine(OutputDir, "network-service.html"), code);
 9
10// Create an instance of Configuration
11using (Configuration configuration = new Configuration())
12{
13    // Add the LogMessageHandler to the chain of existing message handlers
14    INetworkService networkService = configuration.GetService<INetworkService>();
15
16    LogMessageHandler logHandler = new LogMessageHandler();
17    networkService.MessageHandlers.Add(logHandler);
18
19    // Initialize an HTML document with specified configuration
20    using (HTMLDocument document = new HTMLDocument(Path.Combine(OutputDir, "network-service.html"), configuration))
21    {
22        //Convert HTML to PNG
23        Converter.ConvertHTML(document, new ImageSaveOptions(), Path.Combine(OutputDir, "network-service_out.png"));
24
25        // Print the List of ErrorMessages
26        foreach (string errorMessage in logHandler.ErrorMessages)
27        {
28            Console.WriteLine(errorMessage);
29        }
30    }
31}

After the example runs, network-service.html is converted to PNG. The available image is rendered, and unavailable image URLs are written to the ErrorMessages list:

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

Common Environment Configuration Issues

ProblemCauseSolution
Configuration changes have no effectThe HTMLDocument was created before the service property or sandbox flag was changed.Configure services first, then pass the configured Configuration instance to the HTMLDocument constructor.
User stylesheet is ignoredThe CSS was assigned after the document was loaded, or the selector does not match document elements.Set UserStyleSheet before creating the document and verify selectors against the source HTML.
Custom fonts are not usedThe font folder path is wrong, the folder does not contain required fonts, or the runtime environment cannot access it.Use an existing folder with required font files and configure it before rendering. For details, see How to Set Font Folder.
JavaScript runs too longRuntime timeout is not configured, or scripts should be blocked rather than limited.Set IRuntimeService.JavaScriptTimeout for time limits, or use Sandboxing to disable scripts.
Remote resources fail to loadNetwork access, certificates, URLs, or custom handlers block the request.Inspect requests with INetworkService.MessageHandlers or use dedicated Message Handlers examples.

FAQ

What is Configuration used for in Aspose.HTML for .NET?

Configuration defines the environment used when creating an HTMLDocument. It can control sandbox flags, user agent settings, character encoding, fonts, runtime behavior, and network services.

How do I apply a user stylesheet without changing the source HTML?

Get IUserAgentService from the configuration and assign CSS rules to UserStyleSheet before creating the HTMLDocument. The stylesheet is applied during document processing and rendering.

How do I set a custom character encoding?

Set IUserAgentService.CharSet before loading the document. Use this only when the source HTML does not declare the correct encoding or the encoding cannot be detected reliably.

How do I use custom fonts for HTML rendering?

Configure IUserAgentService.FontsSettings.SetFontsLookupFolder(fontFolder) before rendering or conversion. For a full workflow, see How to Set Font Folder.

When should I use Network Service?

Use INetworkService.MessageHandlers when you need request logging, caching, authentication, timeouts, custom schemes, or URL-level request control. For deeper examples, see Message Handlers.

Can one Configuration combine several services?

Yes. A single Configuration instance can combine user agent settings, runtime timeout, sandbox flags, and network message handlers before it is passed to HTMLDocument.

Related Articles

The complete C# examples and data files are available in the Aspose.HTML for .NET GitHub repository.