Загрузка SVG-шрифтов | .NET

Загрузка SVG-шрифтов с помощью Aspose.Font для .NET

Почему SVG-шрифты?

Aspose.Font предоставляет единый, унифицированный API для загрузки любого поддерживаемого типа шрифта (TTF, OTF, WOFF, WOFF2, SVG, …) и работы с ним как со строго типизированным объектом Aspose.Font.Font.

Что требуется

ЭлементОписаниеКак получить
Aspose.Font for .NETБиблиотека ядра, которая читает/записывает все поддерживаемые форматы шрифтов (включая SVG).dotnet add package Aspose.Font
или через UI NuGet: https://www.nuget.org/packages/Aspose.Font/
Target framework.NET Framework 4.x / .NET Core 3.x / .NET 5/6/7 – любая платформа, поддерживаемая Aspose.Font.Дополнительные среды выполнения не требуются.
Namespace importscsharp<br>using Aspose.Font;<br>using Aspose.Font.Sources;<br>using System.IO;<br>

Добавление пакета NuGet

1dotnet add package Aspose.Font

Основные концепции API

Класс / ПеречислениеНазначение
FontDefinitionОписывает что вы хотите загрузить (тип шрифта + источник).
FontFileDefinitionСвязывает источник потока (FileSystemStreamSource, ByteContentStreamSource и др.) с расширением файла ("svg").
FileSystemStreamSource / ByteContentStreamSourceОбеспечивает читаемый поток исходных байтов – либо из файла на диске, либо из буфера в памяти.
Font.Open(FontDefinition)Фабричный метод, который парсит источник и возвращает конкретную реализацию Aspose.Font.Font (SvgFont).

Единственное, что меняется между форматами, — значение перечисления FontType (Svg) и строка расширения файла ("svg").

Загрузка SVG‑шрифта – три распространённых сценария

Загрузка из файловой системы

 1using System;
 2using System.IO;
 3using Aspose.Font;
 4using Aspose.Font.Sources;
 5
 6class LoadSvgFromFile
 7{
 8    static void Main()
 9    {
10        // 1️⃣ Path to the *.svg* file
11        string svgPath = @"C:\Fonts\MyWebFont.svg";
12
13        // Verify the file exists
14        if (!File.Exists(svgPath))
15            throw new FileNotFoundException($"SVG file not found: {svgPath}");
16
17        // 2️⃣ Stream source that reads directly from the file
18        FileSystemStreamSource streamSrc = new FileSystemStreamSource(svgPath);
19
20        // 3️⃣ FontFileDefinition – we tell Aspose the extension is "svg"
21        FontFileDefinition fileDef = new FontFileDefinition("svg", streamSrc);
22
23        // 4️⃣ FontDefinition – specify the exact font type
24        FontDefinition fontDef = new FontDefinition(FontType.Svg, fileDef);
25
26        // 5️⃣ Load the font
27        Font svgFont = Font.Open(fontDef);
28
29        Console.WriteLine($"Loaded font: {svgFont.GetType().Name}");   // → SvgFont
30    }
31}

Result: svgFont is an instance of Aspose.Font.Svg.SvgFont. From here you can query glyphs, metrics, or convert it to another format.

Загрузка из массивa байтов

 1using System;
 2using System.IO;
 3using Aspose.Font;
 4using Aspose.Font.Sources;
 5
 6class LoadSvgFromBytes
 7{
 8    static void Main()
 9    {
10        // Assume the SVG font was bundled as an embedded resource
11        byte[] svgBytes = File.ReadAllBytes(@"C:\Fonts\MyWebFont.svg");
12
13        // Wrap the raw bytes into a stream source
14        ByteContentStreamSource byteSrc = new ByteContentStreamSource(svgBytes);
15
16        // Build the definition – extension still must be “svg”
17        FontDefinition fd = new FontDefinition(
18            FontType.Svg,
19            "svg",
20            byteSrc);
21
22        // Load
23        Font svgFont = Font.Open(fd);
24
25        Console.WriteLine($"Glyph count: {((Aspose.Font.Svg.SvgFont)svgFont).Glyphs.Count}");
26    }
27}

When to use:

Загрузка напрямую из открытого потока

 1using System;
 2using System.IO;
 3using Aspose.Font;
 4using Aspose.Font.Sources;
 5
 6class LoadSvgFromOpenStream
 7{
 8    static void Main()
 9    {
10        using (FileStream fs = File.OpenRead(@"C:\Fonts\MyWebFont.svg"))
11        {
12            // The stream source can be constructed from any Stream object
13            FileSystemStreamSource src = new FileSystemStreamSource(fs);
14
15            // Pass stream source + extension straight into FontDefinition
16            FontDefinition fd = new FontDefinition(
17                FontType.Svg,
18                "svg",
19                src);
20
21            Font svgFont = Font.Open(fd);
22            Console.WriteLine($"Family name: {((Aspose.Font.Svg.SvgFont)svgFont).FamilyNames[0]}");
23        }
24    }
25}

Why this matters:
If you already own a Stream (e.g., from an ASP.NET upload) you don’t need to write it to disk first – just wrap it and open.

All of these scenarios are demonstrated in the official examples repository:

Заключение

With just three lines of code you can pull an SVG font from disk, memory, or any custom stream and instantly gain full programmatic access to its glyph paths, metrics, and conversion capabilities—thanks to Aspose.Font’s unified model. Combine this with Aspose.SVG’s rendering engine if you need to rasterize text directly onto an image or PDF, and you have a complete pipeline for modern web‑centric typography in .NET.

Have any questions about Aspose.Font?



Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.