Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
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 to | Configure |
|---|---|
| Block script execution or another restricted capability | Sandbox flags through Configuration.setSecurity() |
| Apply CSS without modifying the source HTML | IUserAgentService and setUserStyleSheet() |
| Specify a primary character encoding | IUserAgentService.setCharSet() |
| Use fonts from a custom folder | FontsSettings and setFontsLookupFolder() |
| Limit JavaScript execution time | IRuntimeService and setJavaScriptTimeout() |
| Inspect or customize network requests | INetworkService and message handlers |
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:
Configuration instance.configuration.setSecurity(Sandbox.Scripts).HTMLDocument constructor.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.
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.
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:
Configuration instance.IUserAgentService with
getService().setUserStyleSheet().HTMLDocument with the configuration.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");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:
Configuration instance.IUserAgentService from the configuration.setCharSet() with the source encoding.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.
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:
Configuration instance.IUserAgentService from the configuration.FontsSettings object.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.

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:
Configuration instance.IRuntimeService from the configuration.TimeSpan to setJavaScriptTimeout().HTMLDocument constructor.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");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.
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:
MessageHandler subclass and override invoke().Configuration instance.INetworkService from the configuration.getMessageHandlers().HTMLDocument with the configuration. 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");| Issue | Cause and fix |
|---|---|
| Configuration settings have no effect | Configure the service before creating HTMLDocument, and pass that Configuration instance to the document constructor. |
| A user stylesheet does not change the output | Check that setUserStyleSheet() is called before document loading and that its selectors match the source elements. |
| Text contains incorrect characters | Set IUserAgentService.setCharSet() only to the encoding actually used by the source bytes. |
| Custom fonts are not used | Verify the font-folder path, required font files, file permissions, and CSS font-family names. |
| JavaScript still runs too long | Set IRuntimeService.setJavaScriptTimeout(), or block script execution entirely with Sandbox.Scripts. |
| A handler does not receive requests | Add it to INetworkService.getMessageHandlers() before loading the document with the configuration. |
Configuration defines processing settings used by an HTMLDocument, including sandbox flags, user agent settings, fonts, JavaScript runtime limits, and network handlers.
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.
Use Sandbox.Scripts when scripts must not run. Use IRuntimeService.setJavaScriptTimeout() when scripts are allowed but their execution time must be limited.
Get IUserAgentService, access its FontsSettings, and call setFontsLookupFolder() before loading and converting the document.
Add a custom MessageHandler to INetworkService.getMessageHandlers() and inspect response status codes during document loading and conversion.
You can download the complete examples and data files from GitHub.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.