Environment Configuration in Java

Use the Configuration class to define the environment in which Aspose.HTML processes a document. Configure sandbox flags, user styles, character encoding, font lookup folders, JavaScript timeouts, or network handlers before passing the Configuration instance to an HTMLDocument constructor.

Environment configuration helps make HTML loading and rendering consistent across local applications, servers, and containers. Create a Configuration, obtain the required service with getService(), adjust its settings, and then create the HTMLDocument with that configuration.

If you need toConfigure
Block script execution or another restricted capabilitySandbox flags through Configuration.setSecurity()
Apply CSS without modifying the source HTMLIUserAgentService and setUserStyleSheet()
Specify a primary character encodingIUserAgentService.setCharSet()
Use fonts from a custom folderFontsSettings and setFontsLookupFolder()
Limit JavaScript execution timeIRuntimeService and setJavaScriptTimeout()
Inspect or customize network requestsINetworkService and message handlers

Sandboxing

A sandbox flag set restricts selected capabilities of potentially untrusted content. For example, the Sandbox.Scripts flag blocks script execution while Aspose.HTML loads and processes the document.

To disable scripts during HTML processing in Java:

  1. Prepare HTML that contains script content.
  2. Create a Configuration instance.
  3. Call configuration.setSecurity(Sandbox.Scripts).
  4. Load the HTML with the configured HTMLDocument constructor.
  5. Convert the document to the required output format.

The following example blocks scripts before loading the HTML and converting it to PDF. The script does not add its text to the output:

 1// How to disable scripts for HTML to PDF conversion using Java
 2
 3// Prepare HTML code and save it to a file
 4String code = "<span>Hello, World!!</span>\n" +
 5        "<script>document.write('Have a nice day!');</script>\n";
 6
 7try (java.io.FileWriter fileWriter = new java.io.FileWriter("sandboxing.html")) {
 8    fileWriter.write(code);
 9}
10
11// Create an instance of the Configuration class
12Configuration configuration = new Configuration();
13
14// Mark 'scripts' as an untrusted resource
15configuration.setSecurity(com.aspose.html.Sandbox.Scripts);
16
17// Initialize an HTML document with specified configuration
18HTMLDocument document = new HTMLDocument("sandboxing.html", configuration);
19
20// Convert HTML to PDF
21Converter.convertHTML(document, new PdfSaveOptions(), "sandboxing_out.pdf");

Use a JavaScript timeout instead of Sandbox.Scripts when scripts must run but should not execute indefinitely.

User Agent Service

Aspose.HTML groups environment settings into services available from com.aspose.html.services. The User Agent Service controls document-level settings such as a user stylesheet, primary character set, language, and font lookup configuration.

User Style Sheet

A user stylesheet applies CSS through the processing environment without changing the source HTML. Its rules participate in the CSS cascade and can change rendered output.

To apply a custom user stylesheet in Java:

  1. Create a Configuration instance.
  2. Get IUserAgentService with getService().
  3. Pass the required CSS to setUserStyleSheet().
  4. Create an HTMLDocument with the configuration.
  5. Render or convert the configured document.

The example applies span { color: green; } and converts the HTML document to PDF:

 1// Apply a custom user stylesheet to HTML content and convert it to PDF using Java
 2
 3// Prepare HTML code and save it to a file
 4String code = "<span>Hello, World!!!</span>";
 5
 6try (java.io.FileWriter fileWriter = new java.io.FileWriter("user-agent-stylesheet.html")) {
 7    fileWriter.write(code);
 8}
 9
10// Create an instance of the Configuration class
11Configuration configuration = new Configuration();
12
13// Get the IUserAgentService
14IUserAgentService userAgent = configuration.getService(IUserAgentService.class);
15
16// Set a custom color to the <span> element
17userAgent.setUserStyleSheet("span { color: green; }");
18
19// Initialize an HTML document with specified configuration
20HTMLDocument document = new HTMLDocument("user-agent-stylesheet.html", configuration);
21
22// Convert HTML to PDF
23Converter.convertHTML(document, new PdfSaveOptions(), "user-agent-stylesheet_out.pdf");

Character Set

Correct character decoding requires the encoding used by the source content. Set the primary character set manually when the document does not declare its encoding and you know that the source uses a character set other than UTF-8.

To set a character encoding in Java:

  1. Create a Configuration instance.
  2. Get IUserAgentService from the configuration.
  3. Call setCharSet() with the source encoding.
  4. Load the document with the same configuration.
  5. Render or convert the document.

The following example sets ISO-8859-1 as the primary character set before loading the HTML:

 1// Set User Agent charset to ISO-8859-1 and convert HTML to PDF using Java
 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
 7try (java.io.FileWriter fileWriter = new java.io.FileWriter("user-agent-charset.html")) {
 8    fileWriter.write(code);
 9}
10
11// Create an instance of the Configuration class
12Configuration configuration = new Configuration();
13
14// Get the IUserAgentService
15IUserAgentService userAgent = configuration.getService(IUserAgentService.class);
16
17// Set ISO-8859-1 encoding to parse the document
18userAgent.setCharSet("ISO-8859-1");
19
20// Initialize an HTML document with specified configuration
21HTMLDocument document = new HTMLDocument("user-agent-charset.html", configuration);
22
23// Convert HTML to PDF
24Converter.convertHTML(document, new PdfSaveOptions(), "user-agent-charset_out.pdf");

Set the character set to match the actual bytes in the source. Selecting the wrong encoding can produce incorrect characters in parsed or rendered content.

Set a Custom Font Folder

Configure a font lookup folder when the required fonts are not installed in the operating system or available in the container environment.

To use fonts from a custom folder in Java:

  1. Create a Configuration instance.
  2. Get IUserAgentService from the configuration.
  3. Get its FontsSettings object.
  4. Call setFontsLookupFolder() with the font directory.
  5. Load and render the document with the configuration.

The following example points Aspose.HTML to a local fonts folder before converting HTML to PDF:

 1// Set font folder for HTML to PDF conversion using Java
 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
 7try (java.io.FileWriter fileWriter = new java.io.FileWriter("user-agent-fontsetting.html")) {
 8    fileWriter.write(code);
 9}
10
11// Initialize an instance of the Configuration class
12Configuration configuration = new Configuration();
13
14// Get the IUserAgentService
15IUserAgentService userAgent = configuration.getService(IUserAgentService.class);
16
17// Set a custom font folder path
18userAgent.getFontsSettings().setFontsLookupFolder("fonts");
19
20// Initialize an HTML document with specified configuration
21HTMLDocument document = new HTMLDocument("user-agent-fontsetting.html", configuration);
22
23// Convert HTML to PDF
24Converter.convertHTML(document, new PdfSaveOptions(), "user-agent-fontsetting_out.pdf");

The figure illustrates how font and user stylesheet configuration can affect rendered HTML. It is a general comparison of the source and configured output rather than the output of the font-folder snippet alone.

HTML rendering before and after applying font and user stylesheet settings

Runtime Service

The Runtime Service controls runtime-related processing settings. Its setJavaScriptTimeout() method limits how long JavaScript can execute; a script that exceeds the configured TimeSpan is cancelled. The API default is one minute.

To limit JavaScript execution time in Java:

  1. Prepare HTML containing the script to process.
  2. Create a Configuration instance.
  3. Get IRuntimeService from the configuration.
  4. Pass the required TimeSpan to setJavaScriptTimeout().
  5. Load the HTML with the configured HTMLDocument constructor.
  6. Render or convert the document.

The following example sets a five-second timeout, loads HTML containing an endless loop, and calls Converter.convertHTML() to create a PNG image. If the script exceeds the timeout, its execution is cancelled.

 1// Limit JavaScript execution time when converting HTML to image using Java
 2
 3// Prepare 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
 8try (java.io.FileWriter fileWriter = new java.io.FileWriter("runtime-service.html")) {
 9    fileWriter.write(code);
10}
11
12// Create an instance of the Configuration class
13Configuration configuration = new Configuration();
14
15// Limit JS execution time to 5 seconds
16IRuntimeService runtimeService = configuration.getService(IRuntimeService.class);
17runtimeService.setJavaScriptTimeout(TimeSpan.fromSeconds(5));
18
19// Initialize an HTML document with specified configuration
20HTMLDocument document = new HTMLDocument("runtime-service.html", configuration);
21
22// Convert HTML to PNG
23Converter.convertHTML(document, new ImageSaveOptions(), "runtime-service_out.png");

Network Service

The Network Service provides access to the message-handler pipeline used for requests and responses. Custom handlers can inspect requests, log failed resources, implement caching, or add other application-specific network behavior.

Log Failed Resource Requests

Extend MessageHandler and override invoke() to run custom logic during network processing. The following snippet defines a reusable LogMessageHandler class that checks the response status and reports a resource request outside the successful HTTP 2xx range:

 1// Log failed HTTP requests with a custom MessageHandler
 2
 3// Message handler logs all failed requests to the console
 4class LogMessageHandler extends MessageHandler {
 5
 6    @Override
 7    public void invoke(INetworkOperationContext context) {
 8        int statusCode = context.getResponse().getStatusCode();
 9
10        if (statusCode < 200 || statusCode >= 300) {
11            System.out.println(String.format(
12                    "Resource '%s' returned HTTP status %d.",
13                    context.getRequest().getRequestUri(),
14                    statusCode));
15        }
16
17        // Invoke the next message handler in the chain
18        next(context);
19    }
20}

The next example creates a LogMessageHandler instance, adds it to INetworkService, loads HTML containing a missing image, and converts the document to PNG. During processing, the handler writes the resource URL and returned HTTP status to the console.

To register a network message handler in Java:

  1. Implement a reusable MessageHandler subclass and override invoke().
  2. Create a Configuration instance.
  3. Get INetworkService from the configuration.
  4. Add the handler to getMessageHandlers().
  5. Create the HTMLDocument with the configuration.
  6. Process the document and inspect the handler output.
 1// Handle missing image requests with a custom MessageHandler in Aspose.HTML for Java
 2
 3// Prepare HTML code with missing image file
 4String code = "<img src='missing.jpg'>";
 5
 6try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
 7    fileWriter.write(code);
 8}
 9
10// Create an instance of the Configuration class
11Configuration configuration = new Configuration();
12
13// Add ErrorMessageHandler to the chain of existing message handlers
14INetworkService network = configuration.getService(INetworkService.class);
15LogMessageHandler logHandler = new LogMessageHandler();
16network.getMessageHandlers().addItem(logHandler);
17
18// Initialize an HTML document with specified configuration
19// During the document loading, the application will try to load the image and we will see the result of this operation in the console
20HTMLDocument document = new HTMLDocument("document.html", configuration);
21
22// Convert HTML to PNG
23Converter.convertHTML(document, new ImageSaveOptions(), "output.png");

Common Environment Configuration Issues

IssueCause and fix
Configuration settings have no effectConfigure the service before creating HTMLDocument, and pass that Configuration instance to the document constructor.
A user stylesheet does not change the outputCheck that setUserStyleSheet() is called before document loading and that its selectors match the source elements.
Text contains incorrect charactersSet IUserAgentService.setCharSet() only to the encoding actually used by the source bytes.
Custom fonts are not usedVerify the font-folder path, required font files, file permissions, and CSS font-family names.
JavaScript still runs too longSet IRuntimeService.setJavaScriptTimeout(), or block script execution entirely with Sandbox.Scripts.
A handler does not receive requestsAdd it to INetworkService.getMessageHandlers() before loading the document with the configuration.

FAQ

What does Configuration control in Aspose.HTML for Java?

Configuration defines processing settings used by an HTMLDocument, including sandbox flags, user agent settings, fonts, JavaScript runtime limits, and network handlers.

When should I configure services?

Configure the required services first and then pass the same Configuration instance to the HTMLDocument constructor. Changes made too late may not affect document loading or rendering.

Should I block JavaScript or set a timeout?

Use Sandbox.Scripts when scripts must not run. Use IRuntimeService.setJavaScriptTimeout() when scripts are allowed but their execution time must be limited.

How do I use custom fonts when converting HTML?

Get IUserAgentService, access its FontsSettings, and call setFontsLookupFolder() before loading and converting the document.

How can I detect missing images or stylesheets?

Add a custom MessageHandler to INetworkService.getMessageHandlers() and inspect response status codes during document loading and conversion.

Other Platforms

Related Articles

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