环境配置 – Aspose.SVG for .NET

环境配置的设置用于多种目的。例如,当您开发应用程序时,您肯定会需要一些配置,范围从运行时服务或处理来自应用程序的任何 Web 请求到注入自定义主题。

在本指南中,您将学习如何创建各种配置并使它们适应应用程序运行的不同环境。这可以是自定义主题、运行时服务或 Web 请求网络服务。

Aspose.Svg.Services 命名空间包含一组用于分离服务实现的接口。本文考虑不同类型的环境配置服务,例如用户代理服务运行时服务网络服务。 Aspose.SVG for .NET提供了 Configuration类,可用于设置应用程序运行的环境。

您可以从 GitHub 下载完整的示例和数据文件。您可以从 如何运行示例 部分了解如何从 GitHub 下载并运行示例。

用户代理服务 – User Agent Service

用户代理服务允许您指定自定义用户样式表、文档的主要字符集、语言和字体设置。您可以为特定文档选择自定义样式信息,并根据需要提供尽可能少或任意多的环境配置更改。

IUserAgentService 接口描述用户代理环境。

考虑一个说明 UserStyleSheetCharSetFontsSettings 属性应用的示例:

1using System.IO;
2using Aspose.Svg;
3using Aspose.Svg.Services;
4using Aspose.Svg.Converters;
5using Aspose.Svg.Saving;
 1// Set custom user agent, styles, charset, and fonts for SVG conversion to PDF in C#
 2
 3// Prepare SVG code and save it to a file
 4string code = "<svg xmlns=\"http://www.w3.org/2000/svg\">\r\n" +
 5              "    <circle cx=\"40\" cy=\"80\" r=\"30\" />\r\n" +
 6              "    <text x=\"80\" y=\"100\">Aspose.SVG</text>\r\n" +
 7              "</svg>\r\n";
 8
 9File.WriteAllText(Path.Combine(OutputDir, "user-agent.svg"), code);
10
11// Create an instance of the Configuration class
12using (Configuration configuration = new Configuration())
13{
14    // Get the IUserAgentService
15    IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
16
17    // Set a custom style parameters for <circle> and <text> elements
18    userAgentService.UserStyleSheet = "circle { fill:silver; }\r\n" +
19                                      "text { fill:DarkCyan; font-size:3em; }\r\n";
20
21    // Set ISO-8859-1 encoding to parse a document
22    userAgentService.CharSet = "ISO-8859-1";
23
24    // Set a custom font folder path
25    userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir + "fonts"));
26
27    // Initialize an SVG document with specified configuration
28    using (SVGDocument document = new SVGDocument(Path.Combine(OutputDir, "user-agent.svg"), configuration))
29    {
30        // Convert SVG to PDF
31        Converter.ConvertSVG(document, new PdfSaveOptions(), Path.Combine(OutputDir, "user-agent.pdf"));
32    }
33}

该图说明了 用户代理服务 将 (b) 应用于源 user-agent.svg 文件 (a) 的结果。

文本“user-agent.svg 和 user-agent.pdf 文件的渲染”

运行时服务 – Runtime Service

当计划运行应用程序时,您可能需要运行时服务配置。该服务使您可以控制内部流程的生命周期。例如,使用 IRuntimeService,您可以指定 JavaScript 的超时。如果脚本包含无限循环,那么设置这样的超时非常重要。下一个代码片段演示了如何使用超时。

1using System.IO;
2using Aspose.Svg;
3using Aspose.Svg.Services;
4using Aspose.Svg.Converters;
5using Aspose.Svg.Saving;
 1// Limit JavaScript execution time in SVG before conversion to PNG in C#
 2
 3// Prepare SVG code and save it to a file
 4string code = "<svg xmlns=\"http://www.w3.org/2000/svg\">\r\n" +
 5              "    <script> while(true) {} </script>\r\n" +
 6              "    <circle cx=\"40\" cy=\"80\" r=\"30\" />\r\n" +
 7              "</svg>\r\n";
 8
 9File.WriteAllText(Path.Combine(OutputDir, "runtime.svg"), code);
10
11// Create an instance of the Configuration class
12using (Configuration configuration = new Configuration())
13{
14    // Limit JS execution time to 5 seconds
15    IRuntimeService runtimeService = configuration.GetService<IRuntimeService>();
16    runtimeService.JavaScriptTimeout = TimeSpan.FromSeconds(5);
17                   
18    // Initialize an SVG document with specified configuration
19    using (SVGDocument document = new SVGDocument(Path.Combine(OutputDir, "runtime.svg"), configuration))
20    {
21        // Convert SVG to PNG
22        Converter.ConvertSVG(document, new ImageSaveOptions(), Path.Combine(OutputDir, "runtime.png"));
23    }
24}

JavaScriptTimeout 属性设置 TimeSpan,它限制 JavaScript 的执行时间。如果脚本的执行时间超过了提供的 TimeSpan,它将被取消。默认值为 1 分钟。

网络服务 – Network Service

现代网络环境通过网络路由器和交换机、服务器、反恶意软件系统等生成大量安全事件和日志数据。

Aspose.SVG for .Net 提供了 INetworkService,它被设想为帮助管理和分析所有这些信息的解决方案。服务允许您控制所有传入/传出流量并实现自定义消息处理程序。它可用于不同的目的,例如创建自定义缓存机制、跟踪/记录请求消息等。

创建自定义消息处理程序

Aspose.SVG for .NET 提供了创建自定义消息处理程序的功能。让我们开发一个简单的自定义处理程序来记录有关无法访问的资源的信息。采取以下步骤:

  1. 使用必要的命名空间,即 Aspose.Svg.Net。该命名空间由类和接口表示,负责帮助轻松进行网络处理。
  2. 要创建自定义消息处理程序,您需要定义自己的类,该类将从 MessageHandler 类派生。我们构造一个 LogMessageHandler 类。
  3. 重写 MessageHandler 类的 Invoke() 方法以实现自定义消息处理程序行为。

以下示例演示如何创建 LogMessageHandler 来记录有关无法访问的资源的信息。

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

有关创建自定义消息处理程序的更多信息,请参阅章节 消息处理程序

使用 LogMessageHandler 记录有关无法访问的资源的信息

以下示例演示如何使用 LogMessageHandler 类来记录有关无法访问的资源的信息。

1using System.IO;
2using Aspose.Svg;
3using Aspose.Svg.Services;
4using Aspose.Svg.Converters;
5using Aspose.Svg.Saving;
6using Aspose.Svg.Net;
 1// Log network errors when loading external images in SVG and convert to PNG
 2
 3// Prepare SVG code and save it to a file
 4string code = "<svg xmlns=\"http://www.w3.org/2000/svg\">\r\n" +
 5              "    <image href=\"https://docs.aspose.com/svg/images/drawing/park.jpg\" width=\"640px\" height=\"480px\" />\r\n" +
 6              "    <image href=\"https://docs.aspose.com/svg/net/missing1.svg\" width=\"400px\" height=\"300px\" />\r\n" +
 7              "    <image href=\"https://docs.aspose.com/svg/net/missing2.svg\" width=\"400px\" height=\"300px\" />\r\n" +
 8              "</svg>\r\n";
 9
10File.WriteAllText(Path.Combine(OutputDir, "network.svg"), code);
11
12// Create an instance of the Configuration class
13using (Configuration configuration = new Configuration())
14{
15    // Add LogMessageHandler to the chain of existing message handlers
16    INetworkService networkService = configuration.GetService<INetworkService>();
17    
18    LogMessageHandler logHandler = new LogMessageHandler();
19    networkService.MessageHandlers.Add(logHandler);
20
21    // Initialize an SVG document with specified configuration
22    using (SVGDocument document = new SVGDocument(Path.Combine(OutputDir, "network.svg"),  configuration))
23    {
24        // Convert SVG to PNG
25        Converter.ConvertSVG(document, new ImageSaveOptions(), Path.Combine(OutputDir, "network.png"));
26
27        // Print the List of ErrorMessages
28        foreach (string errorMessage in logHandler.ErrorMessages)
29        {
30            Console.WriteLine(errorMessage);
31        }
32    }
33}

示例运行后:

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

您可以从 GitHub 下载完整的示例和数据文件。关于从 GitHub 下载并运行示例,您可以从 如何运行示例 部分找到。

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.