Skip to content

ducseul/FontBundle

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 

Repository files navigation

FontBundle

A library-agnostic font resource management library for Java. Provides easy access to bundled TTF fonts for use with AWT/Swing, iText, PDFBox, Apache FOP, and other font-consuming libraries.

Features

  • Load fonts from classpath resources
  • Library-agnostic design - works with any PDF/font library
  • Built-in caching for optimal performance
  • Java 8+ compatible
  • Minimal dependencies (Lombok, SLF4J)
  • Type-safe font references via enum
  • Font metadata extraction (name, family, style)
  • Font family grouping with style variants
  • System font registration for AWT/Swing
  • Font validation utilities

Installation

Maven

<dependency>
    <groupId>com.ds.fontbundle</groupId>
    <artifactId>FontBundle</artifactId>
    <version>1.0</version>
</dependency>

Quick Start

Using FontResource (Recommended for PDF libraries)

import com.ds.fontbundle.FontResource;
import com.ds.fontbundle.BundledFont;

// Load font resource
FontResource resource = FontResource.of(BundledFont.ARIAL);

        // Get raw bytes
        byte[] fontBytes = resource.getBytes();

        // Get fresh InputStream
        InputStream stream = resource.newInputStream();

Using FontLoader (For AWT/Swing)

import com.ds.fontbundle.FontLoader;
import com.ds.fontbundle.BundledFont;

import java.awt.Font;

// Get AWT font with size
Font font = FontLoader.getAwtFont(BundledFont.ARIAL, 12f);

        // Get AWT font with style and size
        Font boldFont = FontLoader.getAwtFont(BundledFont.ARIAL_BOLD, Font.BOLD, 14f);

Available Fonts

Enum Constant Font
ARIAL Arial Regular
ARIAL_BOLD Arial Bold
ARIAL_ITALIC Arial Italic
ARIAL_BOLD_ITALIC Arial Bold Italic
TIMES_NEW_ROMAN Times New Roman Regular
TIMES_NEW_ROMAN_BOLD Times New Roman Bold
TIMES_NEW_ROMAN_ITALIC Times New Roman Italic
TIMES_NEW_ROMAN_BOLD_ITALIC Times New Roman Bold Italic

Usage Examples

iText 7

FontResource resource = FontResource.of(BundledFont.ARIAL);
PdfFont font = PdfFontFactory.createFont(resource.getBytes(), PdfEncodings.IDENTITY_H);

iText 5 / OpenPDF

FontResource resource = FontLoader.getFontResource(BundledFont.ARIAL);
BaseFont baseFont = BaseFont.createFont(
    "arial.ttf",
    BaseFont.IDENTITY_H,
    BaseFont.EMBEDDED,
    true,
    resource.getBytes(),
    null
);

PDFBox

FontResource resource = FontResource.of(BundledFont.ARIAL);
PDFont font = PDType0Font.load(document, resource.newInputStream());

Apache FOP

FontResource resource = FontResource.of(BundledFont.ARIAL);
// Use resource.newInputStream() or resource.getBytes() with FOP font configuration

AWT/Swing

Font font = FontLoader.getAwtFont(BundledFont.TIMES_NEW_ROMAN, 16f);
graphics.setFont(font);
graphics.drawString("Hello World", 100, 100);

Font Metadata Extraction

import com.ds.fontbundle.FontMetadata;

FontMetadata metadata = FontMetadata.of(BundledFont.ARIAL_BOLD);
System.out.println("Font: " + metadata.getFontName());
System.out.println("Family: " + metadata.getFamily());
System.out.println("Bold: " + metadata.isBold());
System.out.println("Italic: " + metadata.isItalic());
System.out.println("Style: " + metadata.getStyleName()); // "Bold"
System.out.println("Glyphs: " + metadata.getNumGlyphs());

Font Family Grouping

import com.ds.fontbundle.FontFamily;

// Get all variants of a font family
FontFamily arial = FontFamily.ARIAL;
BundledFont regular = arial.getRegular();
BundledFont bold = arial.getBold();
BundledFont italic = arial.getItalic();
BundledFont boldItalic = arial.getBoldItalic();

// Get variant by style
BundledFont font = arial.getVariant(true, false); // bold, not italic

// Get variant by AWT style constant
BundledFont font2 = arial.getVariant(Font.BOLD | Font.ITALIC);

// Find family by font
FontFamily family = FontFamily.of(BundledFont.ARIAL_BOLD).orElse(null);

// Find family by name
FontFamily times = FontFamily.byName("Times New Roman").orElse(null);

// Get all variants as list
List<BundledFont> allVariants = arial.getAllVariants();

System Font Registration

// Register a single font with AWT GraphicsEnvironment
FontLoader.registerFont(BundledFont.ARIAL);

// Register multiple fonts
FontLoader.registerFonts(BundledFont.ARIAL, BundledFont.ARIAL_BOLD);

// Register entire font family
FontLoader.registerFamily(FontFamily.ARIAL);

// Register all bundled fonts
FontLoader.registerAllFonts();

// Check if font is available in system
boolean available = FontLoader.isFontAvailable("Arial");

// Get all available font family names
String[] families = FontLoader.getAvailableFontFamilyNames();

Font Validation

import com.ds.fontbundle.FontValidator;
import com.ds.fontbundle.FontValidator.ValidationResult;

// Validate a single font
ValidationResult result = FontValidator.validate(BundledFont.ARIAL);
if (result.isValid()) {
    System.out.println("Font: " + result.getFontName());
    System.out.println("Family: " + result.getFontFamily());
    System.out.println("Glyphs: " + result.getNumGlyphs());
    System.out.println("Size: " + result.getFileSize() + " bytes");
} else {
    System.out.println("Error: " + result.getErrorMessage());
}

// Get summary string
System.out.println(result.getSummary());

// Quick validation check
boolean isValid = FontValidator.isValid(BundledFont.ARIAL);

// Validate all fonts
List<ValidationResult> results = FontValidator.validateAll();

// Validate font family
List<ValidationResult> familyResults = FontValidator.validateFamily(FontFamily.ARIAL);

// Check if all fonts are valid
boolean allValid = FontValidator.areAllValid();

API Reference

FontResource

Method Description
FontResource.of(BundledFont) Factory method to create FontResource
getBytes() Get raw font bytes as byte array
newInputStream() Create fresh InputStream for font data
getResourcePath() Get classpath resource path
getFontName() Get font name (enum constant name)
getSize() Get byte array length

FontLoader

Method Description
getAwtFont(BundledFont, float size) Get AWT Font with PLAIN style
getAwtFont(BundledFont, int style, float size) Get AWT Font with specified style
getFontResource(BundledFont) Get cached FontResource
getResourcePath(BundledFont) Get classpath resource path
getResourceAsStream(BundledFont) Get InputStream for font file
clearCache() Clear font caches
registerFont(BundledFont) Register font with system GraphicsEnvironment
registerFonts(BundledFont...) Register multiple fonts
registerFamily(FontFamily) Register all fonts in a family
registerAllFonts() Register all bundled fonts
isFontAvailable(String) Check if font is available in system
getAvailableFontFamilyNames() Get all available system font names

BundledFont

Enum containing all available bundled fonts. Each constant has a getResourcePath() method returning the classpath location of the TTF file.

FontFamily

Method Description
getRegular() Get regular variant
getBold() Get bold variant
getItalic() Get italic variant
getBoldItalic() Get bold italic variant
getAllVariants() Get all variants as list
getVariant(boolean, boolean) Get variant by bold/italic flags
getVariant(int) Get variant by AWT style constant
getDisplayName() Get human-readable family name
contains(BundledFont) Check if font belongs to family
FontFamily.of(BundledFont) Find family containing font
FontFamily.byName(String) Find family by display name
FontFamily.getAllFamilies() Get all font families

FontMetadata

Method Description
FontMetadata.of(BundledFont) Extract metadata from bundled font
FontMetadata.of(FontResource) Extract metadata from FontResource
FontMetadata.of(byte[]) Extract metadata from raw bytes
getFontName() Get font name
getFamily() Get font family
getPsName() Get PostScript name
isBold() Check if bold
isItalic() Check if italic
isPlain() Check if plain (not bold/italic)
isBoldItalic() Check if bold and italic
getStyleName() Get style as string ("Regular", "Bold", etc.)
getNumGlyphs() Get number of glyphs

FontValidator

Method Description
validate(BundledFont) Validate bundled font, returns ValidationResult
validate(byte[]) Validate font from bytes
validateAll() Validate all bundled fonts
validateFamily(FontFamily) Validate all fonts in family
isValid(BundledFont) Quick validity check
areAllValid() Check if all bundled fonts are valid

ValidationResult

Method Description
isValid() True if font is valid
isResourceFound() True if resource file exists
isParseable() True if font file is parseable
getFontName() Get parsed font name
getFontFamily() Get parsed font family
getNumGlyphs() Get glyph count
getFileSize() Get file size in bytes
getErrorMessage() Get error message if invalid
getSummary() Get human-readable summary

Adding New Fonts

  1. Place TTF file in src/main/resources/fonts/[FontFamily]/
src/main/resources/fonts/
├── Arial/
│   └── arial.ttf
├── TimesNewRoman/
│   └── times.ttf
└── YourFont/
    └── yourfont.ttf
  1. Add new enum constant in BundledFont.java:
public enum BundledFont {
    // Existing fonts...

    // Your new font
    YOUR_FONT("fonts/YourFont/yourfont.ttf"),
    YOUR_FONT_BOLD("fonts/YourFont/yourfontbd.ttf");

    // ...
}
  1. Use the new font:
FontResource resource = FontResource.of(BundledFont.YOUR_FONT);

Architecture

                    BundledFont (Enum)
                          │
          ┌───────────────┼───────────────┐
          ▼               ▼               ▼
    FontResource    FontMetadata    FontValidator
    (Byte wrapper)  (Info extract)  (Validation)
          │               │
          └───────┬───────┘
                  ▼
    FontLoader (Utility API with caching & registration)
                  │
                  ▼
    FontFamily (Family grouping)
                  │
                  ▼
    Applications (AWT/iText/PDFBox/etc.)

Error Handling

All font loading failures throw FontLoadException (unchecked):

try {
    FontResource resource = FontResource.of(BundledFont.ARIAL);
} catch (FontLoadException e) {
    // Handle font loading error
    log.error("Failed to load font", e);
}

Dependencies

Dependency Version Scope
Lombok 1.18.30 provided
SLF4J API 2.0.9 compile

Requirements

  • Java 8 or higher
  • Maven 3.x

License

Copyright Ducseul. All rights reserved.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages