环境配置
根据应用程序的环境进行不同的配置是非常有益的。例如,环境配置允许您自定义脚本策略、使用用户定义的样式表覆盖文档样式或处理 Web 请求。为了满足这些要求,Aspose.HTML for Java 提供了专门设计的 Configuration 类。通过使用 “Configuration “对象,您可以毫不费力地根据您的特定需求定制 Java 应用程序的行为。
沙箱 – Sandboxing
沙箱标志*集是一组零个或多个标志,用于限制潜在不信任资源的功能。沙箱通过将潜在的恶意代码或不受信任的代码与底层系统和敏感数据隔离,提供了一个安全可控的执行环境。
下面的 Java 示例演示了如何将 HTML 文档转换为 PDF 格式并应用沙盒限制 – 如何将 Scripts 标记为不可信任的资源。因此,Scripts 在应用程序执行期间将被禁用。
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");在示例中,创建了一个新的 Configuration 类实例来配置沙箱。配置 对象会调用 setSecurity() 方法,并将 com.aspose.html.Sandbox.Scripts 作为参数传递。此标记可启用沙箱并限制在 HTML 文档中执行脚本。
用户代理服务 – User Agent Service
为了便于使用,所有重要功能都被归类到独立的服务中,并放置在软件包 com.aspose.html.services 中。在环境配置方面,User Agent Service允许您指定自定义用户样式表、文档的主要字符集、语言和字体设置。
用户样式表
用户可以为特定文档指定自定义样式信息。这些信息根据 层叠规则 应用于文档,并可能影响文档的显示效果。下面的 Java 代码片段展示了如何使用用户代理服务( IUserAgentService)将用户自定义样式表应用于 HTML 文档,然后将其转换为 PDF。
让我们来看看在 HTML 文档中指定自定义样式表的必要步骤:
- 在示例中,我们使用
Configuration()构造函数创建了一个 Configuration 类的实例。 - 然后,我们调用 Configuration 类上的
getService() 方法,并将
IUserAgentService.class作为参数传递给它。这样,我们就得到了用户代理服务的一个实例。 - 要设置应用于 HTML 文档的自定义用户样式表,我们需要使用用户代理服务的
setUserStyleSheet()方法,并提供 CSS 代码作为参数。在本例中,CSS 规则span { color: green; }用于使所有<span>元素显示绿色文本。
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");字符集
为了正确解析和显示 HTML 文档,应用程序必须知道文档使用的字符集(编码)。如果文档的标题中没有直接指定字符编码,Aspose.HTML 将使用 HTML5 规范默认定义的 UTF-8。不过,如果您确定 HTML 文档的编写方式与 UTF-8 编码不同,也可以手动指定。让我们来看看在 HTML 文档中指定字符集(编码)的必要步骤:
- 创建 Configuration 类的实例。
- 使用
getService() 方法获取用户代理服务的实例。该方法将
IUserAgentService.class作为参数。 - 调用用户代理服务的
setCharSet()方法,并提供所需的字符集(编码)。在本例中,“ISO-8859-1 “被设置为字符集。
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");通过使用 setCharSet() 方法设置字符集,应用程序会告知 Aspose.HTML for Java 解析和渲染引擎 HTML 文档中使用的特定编码。这一点非常重要,因为不同的字符集会以不同的方式表示字符,如果没有正确的编码信息,可能无法准确地解析或显示文档。
设置字体文件夹路径
Aspose.HTML 的主要功能之一是能够使用自定义字体,允许开发人员在渲染过程中添加自己的字体。如果需要使用自定义字体而不是操作系统安装的字体,可以设置自定义文件夹的路径,如下所示:
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");要使用 Aspose.HTML for Java 设置字体文件夹,我们需要使用 FontsSettings 类中的 setFontsLookupFolder() 方法。该方法允许您指定自定义字体所在的文件夹。通过设置字体文件夹,Aspose.HTML 将在渲染 HTML 文档时查找指定文件夹中的字体。
图中展示了将 FontsSettings 和 UserStyleSheet 应用于源文件 “user-agent-fontsetting.html”(a)的结果(b)。

运行时服务 – Runtime Service
运行时服务可让您控制内部进程的生命周期。例如,使用 IRuntimeService 可以为 JavaScripts 指定超时时间。在脚本包含无尽循环的情况下,指定超时非常重要。下面的代码片段演示了如何使用运行时服务限制 JavaScript 的执行时间,并将 HTML 文档转换为图像格式:
- 在示例中,我们从头开始创建 HTML 文档。准备好的 HTML 代码包括
<script>元素中的一个无限循环。我们使用FileWriter()将 HTML 代码写入文件。 - 创建 Configuration 类的实例。
- 调用 getService() 方法获取运行时服务的实例。
- 使用运行时服务的
setJavaScriptTimeout()方法指定允许的最大 JavaScript 代码执行时间。示例设置为 5 秒。 - 使用 HTMLDocument(address, configuration) 构造函数创建 HTMLDocument 对象。它需要先前创建的 HTML 文件的路径和配置对象。
- 使用 convertHTML(document, options, outputPath) 方法将 HTML 转换为 PNG。
在示例中,如果在 JavaScript 执行过程中超过 5 秒的超时时间,Aspose.HTML for Java 将中断 JavaScript 代码的执行,继续执行剩余的 HTML 到 PNG 的转换过程。
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
通过 INetworkService,您可以控制所有传入/传出流量,并实现自定义消息处理程序。它可以用于不同的目的,例如:创建自定义缓存机制、跟踪/记录请求消息等。
消息处理程序
使用
MessageHandler 类并覆盖 invoke() 方法,可以定义在网络操作期间执行的自定义逻辑。下面的示例演示了如何使用消息处理程序记录无法访问资源的信息。在该示例中,逻辑检查响应状态代码并处理未找到文件的情况:
1// Log failed HTTP requests with a custom MessageHandler
2
3// Message handler logs all failed requests to the console
4MessageHandler handler = new MessageHandler() {
5 @Override
6 public void invoke(INetworkOperationContext context) {
7 if (context.getResponse().getStatusCode() != HttpURLConnection.HTTP_OK) {
8 System.out.println(String.format("File '%s' Not Found", context.getRequest().getRequestUri().toString()));
9 }
10
11 // Invoke the next message handler in the chain
12 next(context);
13 }
14};首先,您需要创建一个自定义消息处理程序并使用它,如下所示:
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");结论
Aspose.HTML for Java 中的环境配置功能允许开发人员微调应用程序的行为以满足特定要求。使用 Configuration 类及其相关服务,您可以有效地管理安全、定制、字符编码、字体设置、运行时和网络操作等关键方面。
- 沙盒通过限制潜在有害脚本的执行来提高安全性。
- 用户代理服务允许自定义样式、字符集和字体,提供量身定制的文档渲染体验。
- 运行时服务可控制 JavaScript 的执行时间,防止出现无响应或恶意脚本。
- 网络服务通过提供强大的日志记录、缓存和流量控制功能,方便对网络请求进行定制化处理。
您可以从 GitHub 下载完整的示例和数据文件。