Carregando fontes SVG | .NET

Carregando fontes SVG com Aspose.Font para .NET

Por que fontes SVG?

Aspose.Font fornece uma API única e unificada para carregar qualquer tipo de fonte suportado (TTF, OTF, WOFF, WOFF2, SVG, …) e trabalhá‑la como um objeto Aspose.Font.Font fortemente tipado.

O que você precisa

ItemDescriçãoComo obter
Aspose.Font for .NETBiblioteca principal que lê/escreve todos os formatos de fonte suportados (incluindo SVG).dotnet add package Aspose.Font
ou via a UI do NuGet: https://www.nuget.org/packages/Aspose.Font/
Target framework.NET Framework 4.x / .NET Core 3.x / .NET 5/6/7 – qualquer plataforma suportada pelo Aspose.Font.Não é necessário runtime adicional.
Namespace importscsharp<br>using Aspose.Font;<br>using Aspose.Font.Sources;<br>using System.IO;<br>

Adicionar o pacote NuGet

1dotnet add package Aspose.Font

Conceitos principais da API

Classe / EnumPropósito
FontDefinitionDescreve o que você deseja carregar (tipo de fonte + origem).
FontFileDefinitionAssocia uma fonte de fluxo (FileSystemStreamSource, ByteContentStreamSource, etc.) ao extensão de arquivo ("svg").
FileSystemStreamSource / ByteContentStreamSourceFornece um fluxo legível dos bytes subjacentes – seja a partir de um arquivo no disco ou de um buffer em memória.
Font.Open(FontDefinition)Método de fábrica que analisa a origem e devolve uma implementação concreta de Aspose.Font.Font (SvgFont).

A única coisa que muda entre os formatos é o valor enum FontType (Svg) e a string da extensão do arquivo ("svg").

Carregando uma fonte SVG – três cenários comuns

Carregando a partir do sistema de arquivos

 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}

Resultado: svgFont é uma instância de Aspose.Font.Svg.SvgFont. A partir daqui pode consultar glifos, métricas ou convertê‑la para outro formato.

Carregando a partir de um array de bytes

 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}

Quando usar:

Carregando diretamente de um fluxo aberto

 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}

Por que isso importa:
Se já possui um Stream (por exemplo, de um upload ASP.NET) não precisa gravá‑lo no disco primeiro – basta encapsulá‑lo e abrir.

Todos esses cenários são demonstrados no repositório oficial de exemplos:

Conclusão

Com apenas três linhas de código, pode obter uma fonte SVG a partir de disco, memória ou qualquer fluxo personalizado e obter instantaneamente acesso programático completo aos seus caminhos de glifos, métricas e capacidades de conversão — graças ao modelo unificado do Aspose.Font. Combine isso com o engine de renderização do Aspose.SVG se precisar rasterizar texto diretamente numa imagem ou PDF, e tem um pipeline completo para tipografia moderna centrada na web em .NET.

Have any questions about Aspose.Font?



Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.