Mar 12

When using non standard fonts in a PDF we need to embed the font so it is available to whoever is reading that PDF (as they probably will not have the font installed on their system).

iText provides a great library for generating PDF’s using Java. It also includes the ability to embed fonts.

If the font is not installed on your system and you instead have a font file that you want to embed then you need to first register the font with iText FontFactory.

Then get the font from the FontFactory making sure to tell it that you want the font embedded.


import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class EmbedFont {
  public static void main(String[] args) throws Exception {

      // Pass name of font file on command line

      String filename = args[1];

      // Register the font

      FontFactory.register(filename, filename);

      // Get the font NB. last parameter indicates font needs to be embedded

      Font font = FontFactory.getFont(filename, BaseFont.CP1252, BaseFont.EMBEDDED);

      // Lets now use the font to create a PDF

      Document document = new Document();
      PdfWriter.getInstance(document,  new FileOutputStream(filename+".pdf"));
      document.open();
      Paragraph p = new Paragraph("This uses an embedded font", font);
      document.add(p);
      document.close();
  }
}

written by objects \\ tags: , , , , ,

Feb 13

Changing the font of a JTable’s header can be done using the JTableHeader class. The JTableHeader is a JComponent subclass that manages the header of a JTable.

table.getTableHeader().setFont(font);

written by objects \\ tags: , ,

Dec 02

We’ve all seen characters in our text being displayed with squares or questions marks instead of the expected character. Reason for this is the font being used does not include glyphs for the character(s) found in the string.

To display chinese (or any language) text requires a font that supports the characters used by the language. The Font classes canDisplayUpTo() method tests whether that Font is capable of displaying all the characters in a given string.

    	Font[] allFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
    	
    	// The chinese text we will use to test
    	
    	String sample = "\u4e00";    // unicode encoding
    	
    	// Loop for each available font
    	
    	for (int j = 0; j < allFonts.length; j++) {
    		
    		// Test if the font can display the sample text
    		
    	    if (allFonts[j].canDisplayUpTo(sample) == -1) { 
    	        System.out.println(allFonts[j].getFontName());
    	    }
    	}

written by objects \\ tags: , , , ,