字体是一组可打印或可显示的字符,具有不同的样式、粗细等。它们用于根据不同的要求为文档或网页添加不同的外观和感觉。字体文件包含有关字体的设计和其他信息。在本文中,我们将使用字体文件来检测字体是否支持拉丁符号,或者不使用 Java 以编程方式。

用于检测 TrueType 和 Type1 字体中的拉丁符号的 Java API

Aspose.Font for Java 是一个用于处理 TrueTypeCFFType1 等字体的库。API 支持加载、保存和提取有关字体的信息。该 API 还允许您检测字体中对拉丁符号的支持。您可以使用 Maven 下载 API,也可以从 下载 部分下载 JAR。

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>https://repository.aspose.com/repo/</url>
</repository>
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-font</artifactId>
    <version>21.4</version>
</dependency>

使用 Java 检测 TrueType 字体中的拉丁符号

以下是检测特定 TrueType 字体是否支持拉丁符号的步骤。

  • 使用字体文件创建 FontDefinition 类的实例。
  • 使用上一步中创建的 FontDefinition 对象创建 TtfFont 类的实例。
  • 循环遍历不同的代码并将它们解码为字形 ID。
  • 检查字形 ID 是否支持拉丁符号。

以下示例代码显示了如何检测特定 TrueType 字体是否支持拉丁符号。

// 字体文件路径
String fileName = Utils.getDataDir() + "Montserrat-Regular.ttf"; //Font file name with full path

// 加载字体文件
FontDefinition fd = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName)));
TtfFont ttfFont = (TtfFont) Font.open(fd);

boolean latinText = true;

// 检查是否支持拉丁符号
for (int code = 65; code < 123; code++)
{
    GlyphId gid = ttfFont.getEncoding().decodeToGid(code);
    if (gid == null || gid == GlyphUInt32Id.getNotDef())
    {
        latinText = false;
    }
}

if (latinText)
{
    System.out.println(MessageFormat.format("Font {0} supports latin symbols.", ttfFont.getFontName()));
}
else
{
    System.out.println(MessageFormat.format("Latin symbols are not supported by font {0}.", ttfFont.getFontName()));
}

使用 Java 检测 Type1 字体中的拉丁符号

检测 Type1 字体中对拉丁符号的支持的过程类似于 TrueType 字体。唯一的区别是我们将使用 Type1Font 类来访问字体信息。以下是检测 Type1 字体中对拉丁符号的支持的步骤。

  • 使用字体文件创建 FontDefinition 类的实例。
  • 使用上一步创建的 FontDefinition 对象创建 Type1Font 类的实例。
  • 循环遍历不同的代码并将它们解码为字形 ID。
  • 检查字形 ID 是否支持拉丁符号。

以下示例代码显示了如何检测特定 Type1 字体是否支持拉丁符号。

// 字体文件路径
String fileName = Utils.getDataDir() + "courier.pfb"; //Font file name with full path

// 加载字体文件
FontDefinition fd = new FontDefinition(FontType.Type1, new FontFileDefinition("pfb", new FileSystemStreamSource(fileName)));
Type1Font font = (Type1Font) Font.open(fd);

boolean latinText = true;

// 检查是否支持拉丁符号
for (int code = 65; code < 123; code++)
{
    GlyphId gid = font.getEncoding().decodeToGid(code);
    if (gid == null || gid == GlyphUInt32Id.getNotDef())
    {
        latinText = false;
    }
}

if (latinText)
{
    System.out.println(MessageFormat.format("Font {0} supports latin symbols.", font.getFontName()));
}
else
{
    System.out.println(MessageFormat.format("Latin symbols are not supported by font {0}.", font.getFontName()));
}

获得免费许可证

为了在没有评估限制的情况下试用 API,您可以申请 免费的临时许可证

结论

在本文中,您学习了如何使用 Java 检测字体中对拉丁符号的支持。共享代码示例使您能够检测特定字体是否支持拉丁符号。 Aspose.Font for Java 提供了许多使用字体的附加功能,您可以通过访问 官方文档 来详细了解这些功能。如有任何问题,请随时通过我们的 免费支持论坛 与我们联系。

也可以看看