本快速教程将指导您如何使用 Java 获取字体指标。将提供详细描述以及使用 Java 获取字体指标的示例代码,以便首先配置环境,然后您将获得分步过程和工作 Java 代码以加载 PFB字体并获取字体指标。这个检索字体度量的过程可用于任何常见的操作系统,如 Windows、macOS 或 Linux。
使用 Java 获取字体指标的步骤
- 从 Maven 存储库配置 Aspose.Font 库以获取应用程序中的字体指标
- 将示例 PFB 字体文件加载到 FileSystemStreamSource 类对象中以检索指标
- 通过提供 FileSystemStreamSource 对象来声明 FontFileDefinition 类对象
- 初始化 FontDefinition 类对象并设置 FontType 和 FontFileDefinition 对象
- 使用 Font.open 函数加载字体定义并将其转换为 Type1Font
- 使用 Type1Font 对象获取并显示所有所需的字体度量信息
这些步骤描述了加载 PFB 字体文件的分步方法,然后使用一系列不同的类对象来获取字体定义,然后使用 Java 提取字体度量。所有必需的字体规格信息都在 Type1Font 类对象中可用。
使用 Java 检索字体度量的代码
import com.aspose.cells.License; | |
import com.aspose.font.FileSystemStreamSource; | |
import com.aspose.font.Font; | |
import com.aspose.font.FontDefinition; | |
import com.aspose.font.FontFileDefinition; | |
import com.aspose.font.FontType; | |
import com.aspose.font.Type1Font; | |
public class HowToFetchFontMetricsInJava { | |
public static void main(String[] args) throws Exception { //main function for HowToFetchFontMetricsInJava class to get Type1Font Metrics | |
// Instantiate the license for Aspose.Font to avoid trial version limitations before fetching the Font Metrics | |
License licenseFont = new License(); | |
licenseFont.setLicense("Aspose.Font.lic"); | |
// Load the sample Type1Font PFB file into FileSystemStreamSource | |
FileSystemStreamSource fileSystemStreamSource = new FileSystemStreamSource("Type1FontSampleInput.pfb"); | |
// Instantiate FontFileDefinition class object using the FileSystemStreamSource object as argument | |
FontFileDefinition fontFileDefinition = new FontFileDefinition(fileSystemStreamSource); | |
// Instantiate font definition class object by providing the FontType and FontFileDefinition class object | |
FontDefinition fontDefinition = new FontDefinition(FontType.Type1, fontFileDefinition); | |
// Using the font definition, initialize the Type1Font class object | |
Type1Font type1Font = (Type1Font) Font.open(fontDefinition); | |
// Using this TypeFont class object, retrieve the font metrics information and display it on the console | |
System.out.print( | |
"FontName = " + type1Font.getFontName() + | |
", FontGlyphcount = " + type1Font.getNumGlyphs()+ | |
", FontMetricsAscender = " + type1Font.getMetrics().getAscender() + | |
", FontMetricsDescender = " + type1Font.getMetrics().getDescender() + | |
", FontMetricsTypoAscender = " + type1Font.getMetrics().getTypoAscender() + | |
", FontMetricsTypoDescender = " + type1Font.getMetrics().getTypoDescender() + | |
", FontMetricsUnitsPerEM = " + type1Font.getMetrics().getUnitsPerEM() | |
); | |
} | |
} |
在这个示例代码中,我们首先加载 PFB 文件,然后使用 Type1Font 类打开加载的字体定义。 Type1Font 类包含 FontName、NumGlyphs、Ascender、Descender、TypoAscender、TypoDescender 和 UnitsPerEM 等属性。您可以检索这些属性以在控制台上显示或根据您的应用程序要求对其进行处理。
在本教程中,我们已经完成了使用 Java 检索字体度量的步骤。如果您想了解其他功能,例如将 Word 文件转换为 JPG,请参阅 如何在 Java 中将 Word 转换为 JPG 上的文章。