首页 > 解决方案 > 如何从 URL 的 Web 应用程序中的字体文件中获取字体系列?

问题描述

我必须从文件中获取字体系列。我查过了,但所有答案都在使用 WPF :. 我应该怎么办?

FontFamily(Uri, String)在 dot net 文档中找到了。但它在 system.windows.mediaWPFPresentationCore.dll中,在 aspnet 核心应用程序中不可用。

https://docs.microsoft.com/en-us/dotnet/api/system.windows.media.fontfamily.-ctor?view=net-5.0#System_Windows_Media_FontFamily__ctor_System_Uri_System_String _

StackOverflow 中有另一个线程使用 glyphTypeface 但它来自 WPF 中的同一个 dll/命名空间。

字体文件中的字体系列名称

我找到的最佳答案是这个,但是在 C# 中使用指针是非常可怕的。

private static string LoadFontFamilyName(byte[] buffer)
{
  var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);

  try
  {
      var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);
      using var fontCollection = new PrivateFontCollection();
      fontCollection.AddMemoryFont(ptr, buffer.Length);
      return fontCollection.Families[0].Name;
  }
  finally
  {
      handle.Free();
  }

}

有更好的想法吗?

标签: .netasp.net-core.net-5

解决方案


PrivateFontCollection支持AddFontFile(string filename)应该做你想做的方法。查看源代码,这似乎应该适用于 Windows 和 Unix/Linux 系统(只要后者已libgdiplus安装)。


推荐阅读