Java에서 파일, 스트림 및 바이트 배열로 글꼴 로드

Aspose.Font for Java를 사용하여 TrueType (TTF), OpenType (OTF), WOFF/WOFF2, Embedded OpenType (EOT), Type1 및 Compact Font Format (CFF) 글꼴을 프로그래밍 방식으로 로드하고 초기화합니다. 네이티브 Java AWT 또는 운영 체제에 종속된 글꼴 설치에 의존하지 않고 디스크 경로, 시스템 파일, 바이트 스트림 또는 메모리 내 배열에서 글꼴을 원활하게 로드할 수 있습니다.

 

Aspose.Font for Java에서 모든 글꼴을 열고 작업하려면 두 가지 주요 매개 변수가 필요합니다:

  • 글꼴 형식 (FontType): 일반적인 범주를 식별합니다(예: FontType.TTF, FontType.Type1, FontType.CFF).
  • 글꼴 바이너리 소스 (StreamSource/FontFileDefinition): 디스크, 데이터베이스 또는 문서 스트림(예: PDF/DOCX)에 저장되어 있는지 여부와 관계없이 기본 바이너리 스트림을 캡슐화합니다.
  • 중앙 클래스인 FontDefinition은 이러한 매개 변수를 결합하여 Font.open(fontDefinition)이 통합된 com.aspose.font.Font 객체를 반환할 수 있도록 합니다.

java.io.File을 사용하여 글꼴을 로드하는 방법은?

FontFileDefinition(File file)을 사용하여 로컬 디스크 드라이브에 저장된 글꼴을 로드하는 가장 간단한 방법입니다.

import com.aspose.font.*;
import java.io.File;
import java.nio.file.Paths;

public class LoadFontFromFile {
    public static void main(String[] args) {
        // Step 1: Define path to font file
        String fontPath = Paths.get("data", "Montserrat-Regular.ttf").toString();

        // Step 2: Create FontFileDefinition from java.io.File
        FontFileDefinition fileDef = new FontFileDefinition(new File(fontPath));

        // Step 3: Create FontDefinition (extension is auto-detected from FontFileDefinition)
        FontDefinition fontDef = new FontDefinition(FontType.TTF, fileDef);

        // Step 4: Open and load font instance
        Font font = Font.open(fontDef);

        System.out.println("Successfully loaded font: " + font.getFontName());
    }
}

FileSystemStreamSource를 사용하여 글꼴을 로드하는 방법은?

디스크 경로에서 글꼴을 로드할 때 정확한 형식을 감지할 수 있도록 파일 확장자를 명시적으로 처리합니다.

import com.aspose.font.*;
import java.nio.file.Paths;

public class LoadFontFromStreamSource {
    public static void main(String[] args) {
        String fontPath = Paths.get("data", "Montserrat-Regular.ttf").toString();

        // Pass 'ttf' explicitly to ensure proper format mapping
        FontFileDefinition fileDef = new FontFileDefinition("ttf", new FileSystemStreamSource(fontPath));
        FontDefinition fontDef = new FontDefinition(FontType.TTF, fileDef);

        Font font = Font.open(fontDef);
        System.out.println("Loaded Font Name: " + font.getFontName());
    }
}

직접 스트림 소스에서 글꼴을 로드하는 방법(FontFileDefinition 없이)

간소화된 로드를 위해 FileSystemStreamSource를 FontDefinition에 직접 전달합니다.

import com.aspose.font.*;
import java.nio.file.Paths;

public class LoadFontDirectStream {
    public static void main(String[] args) {
        String fontPath = Paths.get("data", "Montserrat-Regular.ttf").toString();

        // Provide FontType, file extension, and StreamSource directly
        FontDefinition fontDef = new FontDefinition(FontType.TTF, "ttf", new FileSystemStreamSource(fontPath));

        Font font = Font.open(fontDef);
        System.out.println("Loaded Font Name: " + font.getFontName());
    }
}

메모리 내 바이트 배열(byte[])에서 글꼴을 로드하는 방법은?

데이터베이스, 네트워크 요청, 클라우드 스토리지 또는 포함된 PDF/DOCX 리소스에서 가져온 글꼴을 ByteContentStreamSource를 사용하여 로드하는 데 적합합니다.

import com.aspose.font.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class LoadFontFromByteArray {
    public static void main(String[] args) throws Exception {
        String fontPath = Paths.get("data", "Montserrat-Regular.ttf").toString();

        // Read font binary data into byte array
        byte[] fontBytes = Files.readAllBytes(Paths.get(fontPath));

        // Initialize FontDefinition with ByteContentStreamSource
        FontDefinition fontDef = new FontDefinition(FontType.TTF, "ttf", new ByteContentStreamSource(fontBytes));

        // Open font from memory
        Font font = Font.open(fontDef);

        System.out.println("Loaded Font from Memory: " + font.getFontName());
    }
}

설치 및 설정

Maven을 통해 Aspose.Font for Java를 프로젝트에 추가합니다.

Package Manager Console Command

<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>Latest</version>
</dependency>

FAQ

1. 글꼴을 로드할 때 FontType과 fileExtension을 모두 전달해야 하는 이유는 무엇인가요?

FontType은 전체적인 형식 계열(예: FontType.TTF)을 나타내지만, 해당 계열에는 여러 개의 서로 다른 파일 형식(.ttf, .eot, .ttc 등)이 포함될 수 있습니다. fileExtension을 지정하면 라이브러리가 해당 특정 컨테이너 형식에 적합한 파서를 사용하도록 할 수 있습니다.

2. 데이터베이스 BLOB 필드에서 직접 글꼴을 로드할 수 있나요?

예. BLOB 데이터를 byte[] 배열로 가져온 다음 ByteContentStreamSource를 사용하여 데이터를 디스크에 쓰지 않고 FontDefinition을 초기화할 수 있습니다.

3. 파일 내부의 특정 오프셋에서 바이너리 데이터가 시작되는 글꼴을 어떻게 로드하나요?

FontFileDefinition(String fileExtension, StreamSource streamSource, long offset) constructor를 사용하고, 글꼴 데이터가 시작되는 바이트 오프셋을 전달합니다.