Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active October 28, 2020 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/a018220e20bd5728294c39d632ebf22b to your computer and use it in GitHub Desktop.
Save aspose-com-gists/a018220e20bd5728294c39d632ebf22b to your computer and use it in GitHub Desktop.
Java examples for Aspose.Font for Java
Aspose.Font for Java
// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
String fileName = Utils.getDataDir() + "OpenSans-Regular.cff"; //Font file name with full path
FontDefinition fd = new FontDefinition(FontType.CFF, new FontFileDefinition("cff", new FileSystemStreamSource(fileName)));
CffFont ttfFont = (CffFont) Font.open(fd);
System.out.println("Font has been loaded");
// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
byte [] fontMemoryData = Utils.getInputFileBytes("OpenSans-Regular.cff");
FontDefinition fd = new FontDefinition(FontType.CFF, new FontFileDefinition("cff", new ByteContentStreamSource(fontMemoryData)));
CffFont ttfFont = (CffFont) Font.open(fd);
System.out.println("Font has been loaded");
// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
byte [] fontMemoryData = Utils.getInputFileBytes("OpenSans-Regular.cff");
FontDefinition fd = new FontDefinition(FontType.CFF, new FontFileDefinition("cff", new ByteContentStreamSource(fontMemoryData)));
CffFont font = (CffFont) Font.open(fd);
System.out.println("Font has been loaded");
//Work with data from just loaded CffFont object
//Save CffFont to disk
//Output Font file name with full path
String outputFile = Utils.getDataDir() + "OpenSans-Regular_out.cff";
font.save(outputFile);
System.out.println("Font has been saved");
// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
String fileName = Utils.getDataDir() + "Montserrat-Regular.ttf"; //Font file name with full path
FontDefinition fd = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName)));
TtfFont ttfFont = (TtfFont) Font.open(fd);
boolean latinText = true;
for (int code = 65; code < 123; code++)
{
GlyphId gid = ttfFont.getEncoding().decodeToGid(code);
if (gid == null || gid == GlyphUInt32Id.getNotDef())
{
latinText = false;
}
}
if (latinText)
{
System.out.println(MessageFormat.format("Font {0} supports latin symbols.", ttfFont.getFontName()));
}
else
{
System.out.println(MessageFormat.format("Latin symbols are not supported by font {0}.", ttfFont.getFontName()));
}
// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
String fileName = Utils.getDataDir() + "Montserrat-Regular.ttf"; //Font file name with full path
FontDefinition fd = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName)));
TtfFont font = (TtfFont) Font.open(fd);
LicenseFlags licenseFlags = null;
if (font.getTtfTables().getOs2Table() != null)
{
licenseFlags = font.getTtfTables().getOs2Table().getLicenseFlags();
}
if (licenseFlags == null || licenseFlags.isFSTypeAbsent())
{
System.out.println(MessageFormat.format("Font {0} has no embedded license restrictions", font.getFontName()));
}
else
{
if (licenseFlags.isEditableEmbedding())
{
System.out.println(MessageFormat.format("Font {0} may be embedded, and may be temporarily loaded on other systems.", font.getFontName())
+ " In addition, editing is permitted, including ability to format new text"
+ " using the embedded font, and changes may be saved.");
}
else if (licenseFlags.isInstallableEmbedding())
{
System.out.println(MessageFormat.format("Font {0} may be embedded, and may be permanently installed", font.getFontName())
+ " for use on a remote systems, or for use by other users.");
}
else if (licenseFlags.isPreviewAndPrintEmbedding())
{
System.out.println(MessageFormat.format("Font {0} may be embedded, and may be temporarily loaded", font.getFontName())
+ " on other systems for purposes of viewing or printing the document.");
}
else if (licenseFlags.isRestrictedLicenseEmbedding())
{
System.out.println(MessageFormat.format("Font {0} must not be modified, embedded or exchanged in any manner", font.getFontName())
+ " without first obtaining explicit permission of the legal owner.");
}
}
// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
String fileName = Utils.getDataDir() + "Montserrat-Regular.ttf"; //Font file name with full path
FontDefinition fd = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName)));
TtfFont font = (TtfFont) Font.open(fd);
String name = font.getFontName();
System.out.println("Font name: " + name);
System.out.println("Glyph count: " + font.getNumGlyphs());
String metrics = MessageFormat.format(
"Font metrics: ascender - {0}, descender - {1}, typo ascender = {2}, typo descender = {3}, UnitsPerEm = {4}",
font.getMetrics().getAscender(), font.getMetrics().getDescender(),
font.getMetrics().getTypoAscender(), font.getMetrics().getTypoDescender(), font.getMetrics().getUnitsPerEM());
System.out.println(metrics);
//Get cmap unicode encoding table from font as object TtfCMapFormatBaseTable to access information about font glyph for symbol 'A'.
//Also check that font has object TtfGlyfTable (table 'glyf') to access glyph.
TtfCMapFormatBaseTable cmapTable = null;
if (font.getTtfTables().getCMapTable() != null)
{
cmapTable = font.getTtfTables().getCMapTable().findUnicodeTable();
}
if (cmapTable != null && font.getTtfTables().getGlyfTable() != null)
{
System.out.println("Font cmap unicode table: PlatformID = " + cmapTable.getPlatformId() +
", PlatformSpecificID = " + cmapTable.getPlatformSpecificId());
//Code for 'A' symbol
char unicode = (char)65;
//Glyph index for 'A'
long glIndex = cmapTable.getGlyphIndex(unicode);
if (glIndex != 0)
{
//Glyph for 'A'
Glyph glyph = font.getGlyphById(glIndex);
if (glyph != null)
{
//Print glyph metrics
System.out.println("Glyph metrics for 'A' symbol:");
String bbox = MessageFormat.format(
"Glyph BBox: Xmin = {0}, Xmax = {1}" + ", Ymin = {2}, Ymax = {3}",
glyph.getGlyphBBox().getXMin(), glyph.getGlyphBBox().getXMax(),
glyph.getGlyphBBox().getYMin(), glyph.getGlyphBBox().getYMax());
System.out.println(bbox);
System.out.println("Width:" + font.getMetrics().getGlyphWidth(new GlyphUInt32Id(glIndex)));
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
String fileName = Utils.getDataDir() + "Montserrat-Regular.ttf"; //Font file name with full path
FontDefinition fd = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new FileSystemStreamSource(fileName)));
TtfFont font = (TtfFont) Font.open(fd);
// 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();
}
// 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));
}
// 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;
}
// For complete examples and data files, please go to https://github.com/aspose-font/Aspose.Font-for-Java
byte[] fontMemoryData = Utils.getInputFileBytes("Montserrat-Regular.ttf"); //Font file name with full path
FontDefinition fd = new FontDefinition(FontType.TTF, new FontFileDefinition("ttf", new ByteContentStreamSource(fontMemoryData)));
TtfFont font = (TtfFont) Font.open(fd);
//Work with data from just loaded TtfFont object
//Save TtfFont to disk
//Output Font file name with full path
String outputFile = Utils.getDataDir() + "Montserrat-Regular_out.ttf";
font.save(outputFile);
// 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);
boolean latinText = true;
for (int code = 65; code < 123; code++)
{
GlyphId gid = font.getEncoding().decodeToGid(code);
if (gid == null || gid == GlyphUInt32Id.getNotDef())
{
latinText = false;
}
}
if (latinText)
{
System.out.println(MessageFormat.format("Font {0} supports latin symbols.", font.getFontName()));
}
else
{
System.out.println(MessageFormat.format("Latin symbols are not supported by font {0}.", font.getFontName()));
}
// 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);
String name = font.getFontName();
System.out.println("Font name: " + name);
System.out.println("Glyph count: " + font.getNumGlyphs());
String metrics = MessageFormat.format(
"Font metrics: ascender - {0}, descender - {1}, typo ascender = {2}, typo descender = {3}, UnitsPerEm = {4}",
font.getMetrics().getAscender(), font.getMetrics().getDescender(),
font.getMetrics().getTypoAscender(), font.getMetrics().getTypoDescender(), font.getMetrics().getUnitsPerEM());
System.out.println(metrics);
// 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);
// 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();
}
// 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 += fontWidthToImageWith(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));
}
// 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment