环境配置 – Environment Configuration – C#
根据应用程序的运行环境进行不同的配置通常很有帮助。例如,您可能希望配置脚本策略、覆盖应用自定义用户样式表的文档样式或处理来自应用程序的任何网络请求。Aspose.HTML for .NET提供的 Configuration类正好可以用于这些目的。
沙箱 – Sandbox
沙盒标志*集是由零个或多个标志组成的集合,用于限制潜在不信任资源的能力。沙盒属性允许你对加载到框架中的内容设置一系列限制,例如阻止表单和脚本。这可以提高当前文档的安全性,尤其是当文档从未经验证的来源加载到框架中时。
下面的示例演示了如何将 Scripts
标记为不信任资源。因此,Scripts
将在应用程序执行期间禁用。
1// Enable sandboxing to restrict script execution when loading HTML
2
3// Prepare HTML code and save it to a file
4string code = "<span>Hello, World!!</span> " +
5 "<script>document.write('Have a nice day!');</script>";
6
7File.WriteAllText(Path.Combine(OutputDir, "sandboxing.html"), code);
8
9// Create an instance of Configuration
10using (Configuration configuration = new Configuration())
11{
12 // Mark 'scripts' as an untrusted resource
13 configuration.Security |= Sandbox.Scripts;
14
15 // Initialize an HTML document with specified configuration
16 using (HTMLDocument document = new HTMLDocument(Path.Combine(OutputDir, "sandboxing.html"), configuration))
17 {
18 // Convert HTML to PDF
19 Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "sandboxing_out.pdf"));
20 }
21}
服务 – Services
为便于使用,所有重要功能都被归类为独立的服务,并置于 Aspose.Html.Services 命名空间中。
用户代理服务 – User Agent Service
用户代理服务允许您指定自定义用户样式表、文档的主要字符集、语言和字体设置。您可以为特定文档指定自定义样式信息,并根据需要提供或多或少的环境配置更改。 IUserAgentService 接口描述了用户代理环境。
用户样式表 – User Style Sheet
用户可以为特定文档指定自定义样式信息。这些信息根据
层叠规则 适用于文档,并可能影响文档的显示效果。下面的代码片段展示了如何使用 UserStyleSheet
属性:
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
CharSet
属性设置文档的主要字符集。为了正确解析和显示 HTML 文档,应用程序必须知道文档使用的字符集(编码)。如果在文档头中没有直接指定字符编码,Aspose.HTML for .NET 将使用 HTML5 规范默认的 UTF-8。但是,如果您确定您的 HTML 文档使用的编码与 UTF-8 不同,您可以手动指定,如下所示。
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}
在上例中,我们使用了 CharSet
和 UserStyleSheet
属性来设置 ISO-8859-1 编码和用户样式。
安装字体文件夹
Aspose.HTML for .NET是一个功能强大的库,用于在.NET应用程序中处理HTML文档。它提供了广泛的功能,使开发人员能够将 HTML 文档呈现为各种输出格式,如 PDF、XPS、DOCX 和图像。Aspose.HTML 的主要功能之一是能够处理自定义字体,使开发人员能够在渲染过程中添加自己的字体。
FontsSettings
属性用于配置字体处理。如果需要使用自定义字体而不是操作系统安装的字体,可以设置自定义文件夹的路径,如下代码片段所示:
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}
要使用 Aspose.HTML for .NET 库设置字体文件夹,我们需要使用
FontsSettings 类中的 SetFontsLookupFolder()
方法。该方法允许您指定自定义字体所在的文件夹。通过设置字体文件夹,Aspose.HTML 将在渲染 HTML 文档时查找指定文件夹中的字体。
图中展示了将 FontsSettings
和 UserStyleSheet
属性 (b) 应用于源文件 “user-agent-fontsetting.html”(a)的结果。
运行时服务 – Runtime Service
该服务可让您控制内部进程的生命周期。例如,使用 IRuntimeService 可以为 JavaScripts 指定超时时间。在脚本包含无尽循环的情况下,这种超时非常重要。下面的代码片段演示了如何使用超时。
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}
网络服务 – Network Service
Aspose.HTML for .NET提供的 INetworkService允许您控制所有传入/传出流量,并实现自定义消息处理程序。它可用于不同的目的,如:创建自定义缓存机制、跟踪/记录请求消息等。
消息处理程序
下面的示例演示了如何创建自定义消息处理程序 – LogMessageHandler,以记录无法访问资源的信息:
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}
下一个代码片段演示了如何使用上一个示例中创建的 LogMessageHandler 类来记录不可用资源的信息。
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}
示例运行后
- 创建的文件
network-service.html
将转换为 PNG。PNG 文件中只有一个图像; - 将打印错误信息列表:
File 'https://docs.aspose.com/html/net/missing1.jpg' Not Found
File 'https://docs.aspose.com/html/net/missing2.jpg' Not Found
您可以使用 GitHub 中的完整 C# 示例从 URL 下载文件。
Aspose.HTML 提供 HTML 网络应用程序,它是免费转换器、合并器、搜索引擎优化工具、HTML 代码生成器、URL 工具等的在线集合。这些应用程序可在任何装有网络浏览器的操作系统上运行,无需安装任何其他软件。无论你身在何处,都能轻松转换、合并、编码、生成 HTML 代码,从网络中提取数据,或从搜索引擎优化的角度分析网页。使用我们的 HTML 网络应用程序集来处理您的日常事务,让您的工作流程天衣无缝!