Render Text with TrueType and Type1 Fonts using Java

render text using font in Java

In the previous article, you have seen how to load CFF, TrueType and Type1 fonts programmatically using Java. Today, we will discuss another interesting feature of our Java font manipulation API – rendering text using fonts. By the end of this article, you will be able to render text using TrueType and Type1 fonts from within your Java applications. So let’s start.

Java Font Manipulation API

Aspose.Font for Java provides you with the features of loading and saving the fonts as well as getting the metrics of the popular font types including CFF, TrueType, OpenType, and Type1. In addition, the API lets you render the text using the provided TrueType or Type1 fonts. You can either install the API using Maven configurations or download the API’s 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>20.10</version>
</dependency>

Implement Text Rendering Method

In order to render the text, Aspose.Font for Java requires you to implement the drawText() method which will draw the provided text. The following is the complete definition of the drawText() method.

// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
static void drawText(String text, IFont font, double fontSize,
Paint backgroundBrush, Paint textBrush, String outFile) throws Exception
{
//Get glyph identifiers for every symbol in text line
GlyphId[] gids = new GlyphId[text.length()];
for (int i = 0; i < text.length(); i++)
gids[i] = font.getEncoding().decodeToGid(text.charAt(i));
// set common drawing settings
double dpi = 300;
double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
// prepare output bitmap
BufferedImage outBitmap = new BufferedImage(960, 720, BufferedImage.TYPE_INT_BGR);
//outBitmap.getRaster().SetResolution((float)dpi, (float)dpi);
java.awt.Graphics2D outGraphics = (java.awt.Graphics2D) outBitmap.getGraphics();
outGraphics.setPaint(backgroundBrush);
outGraphics.fillRect(0, 0, outBitmap.getWidth(), outBitmap.getHeight());
outGraphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
//declare coordinate variables and previous gid
GlyphId previousGid = null;
double glyphXCoordinate = 0;
double glyphYCoordinate = fontSize * resolutionCorrection;
//loop which paints every glyph in gids
for (GlyphId gid : gids)
{
// if the font contains the gid
if (gid != null)
{
Glyph glyph = font.getGlyphAccessor().getGlyphById(gid);
if (glyph == null)
continue;
// path that accepts drawing instructions
GeneralPath path = new GeneralPath();
// Create IGlyphOutlinePainter implementation
GlyphOutlinePainter outlinePainter = new GlyphOutlinePainter(path);
// Create the renderer
IGlyphRenderer renderer = new GlyphOutlineRenderer(outlinePainter);
// get common glyph properties
double kerning = 0;
// get kerning value
if (previousGid != null)
{
kerning = (font.getMetrics().getKerningValue(previousGid, gid) /
glyph.getSourceResolution()) * fontSize * resolutionCorrection;
kerning += fontWidthToImageWdith(font.getMetrics().getGlyphWidth(previousGid),
glyph.getSourceResolution(), fontSize, 300);
}
// glyph positioning - increase glyph X coordinate according to kerning distance
glyphXCoordinate += kerning;
// Glyph placement matrix
TransformationMatrix glyphMatrix =
new TransformationMatrix(
new double[]
{
fontSize*resolutionCorrection,
0,
0,
// negative because of bitmap coordinate system begins from the top
- fontSize*resolutionCorrection,
glyphXCoordinate,
glyphYCoordinate
});
// render current glyph
renderer.renderGlyph(font, gid, glyphMatrix);
// fill the path
path.setWindingRule(GeneralPath.WIND_NON_ZERO);
outGraphics.setPaint(textBrush);
outGraphics.fill(path);
}
//set current gid as previous to get correct kerning for next glyph
previousGid = gid;
}
//Save results
ImageIO.write(outBitmap, "jpg", new File(outFile));
}

The following is a utility method that is used to calculate the glyph width for bitmap coordinate system.

// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
static double fontWidthToImageWidth(double width, int fontSourceResulution, double fontSize, double dpi)
{
double resolutionCorrection = dpi / 72; // 72 is font's internal dpi
return (width / fontSourceResulution) * fontSize * resolutionCorrection;
}

Steps to Render Text with Font in Java

The following are the steps of how to render a specified text as an image file using the above-mentioned darwText() method.

  • Load the font using the FontDefinition class.
  • Access the font using the class such as Type1Font or TtfFont.
  • Call the drawText() method by providing the details in the form of its parameters.

Render Text with TrueType Font using Java

The following code sample shows how to use the drawText() method to render text using a TrueType font. The rendering results will be generated as a JPEG image.

// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
String fileName1 = Utils.getDataDir() + "Montserrat-Bold.ttf"; //Font file name with full path
FontDefinition fd1 = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName1)));
TtfFont font1 = (TtfFont) Font.open(fd1);
String fileName2 = Utils.getDataDir() + "Lora-Bold.ttf"; //Font file name with full path
FontDefinition fd2 = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName2)));
TtfFont font2 = (TtfFont) Font.open(fd2);
try {
drawText("Hello world", font1, 14, java.awt.Color.WHITE, java.awt.Color.BLACK, Utils.getDataDir() + "hello1_montserrat_out.jpg");
drawText("Hello world", font2, 14, java.awt.Color.YELLOW, java.awt.Color.RED, Utils.getDataDir() + "hello2_lora_out.jpg");
} catch (Exception ex) {
ex.printStackTrace();
}

Render Text using Type1 Fonts in Java

The following code sample shows how to render text to a JPEG image with a Type1 font using Java.

// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
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);
try {
drawText("Hello world", font, 14, java.awt.Color.WHITE, java.awt.Color.BLACK, Utils.getDataDir() + "hello1_type1_out.jpg");
drawText("Hello world", font, 14, java.awt.Color.YELLOW, java.awt.Color.RED, Utils.getDataDir() + "hello2_type1_out.jpg");
} catch (Exception ex) {
ex.printStackTrace();
}

Conclusion

In this article, you have seen how to render the text as JPEG images using the TrueType or Type1 font from within the Java applications. In order to learn more about the Java font manipulation API, you can visit the documentation and evaluate the API’s features using source code samples.