Convert TTF to WOFF | Java

Contents
[ ]

If you came across a font you like to use in your interface, and it is only available in TTF format, but you use WOFF in your project, you may need a solution that converts fonts. The following documentation will show you how to easily use the Aspose.Font for Java to transform fonts from True type to WebFont.


Use the following statements:

 
    package com.aspose.font;

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;

    import com.aspose.font.ByteContentStreamSource;
    import com.aspose.font.FileSystemStreamSource;
    import com.aspose.font.Font;
    import com.aspose.font.FontDefinition;
    import com.aspose.font.FontFileDefinition;
    import com.aspose.font.FontSavingFormats;
    import com.aspose.font.FontType;
    import com.aspose.font.TtfFont;

The fundamentals for the conversion are placed in How to convert the font into the desired format? section.

To convert TTF to WOFF you will need to take the following steps:

  1. Open TTF font.

        // Open ttf font
        String fontPath = Paths.get(getDataDir(), "Montserrat-Regular.ttf").toString();
        FontDefinition fontDefinition = new FontDefinition(FontType.TTF, new FontFileDefinition(new FileSystemStreamSource(fontPath)));
        Font font = Font.open(fontDefinition);

  2. Write the settings for the output stream.

        // Woff output settings
        String outPath = Paths.get(getOutputDir(), "TtfToWoff_out1.woff").toString();
        FileOutputStream outStream = new FileOutputStream(outPath);   

  3. Convert font to WOFF.

        // Convert ttf to woff
        font.saveToFormat(outStream, FontSavingFormats.WOFF);

Here the saveToFormat() method of the base abstract Font class instance was used. It takes two arguments: output stream and FontSavingFormats enumeration to choose output font format.