Use DefaultFontMapper : Font « PDF « Java Tutorial






import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.Map;

import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

public class MainClass {
  public static void main(String[] args) throws Exception {
    Document document = new Document(new Rectangle(100, 100));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
        "sun_tutorial_with_text.pdf"));
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    PdfTemplate tp = cb.createTemplate(100, 100);
    DefaultFontMapper mapper = new DefaultFontMapper();
    mapper.insertDirectory("c:/windows/fonts");
    String name;
    Map map = mapper.getMapper();
    for (Iterator i = map.keySet().iterator(); i.hasNext();) {
      name = (String) i.next();
      System.out.println(name + ": "
          + ((DefaultFontMapper.BaseFontParameters) map.get(name)).fontName);
    }
    Graphics2D g2 = tp.createGraphics(100, 100, mapper);
    g2.setColor(Color.black);
    java.awt.Font thisFont = new java.awt.Font("Garamond", java.awt.Font.PLAIN, 18);
    g2.setFont(thisFont);
    String pear = "Pear";
    FontMetrics metrics = g2.getFontMetrics();
    int width = metrics.stringWidth(pear);
    g2.drawString(pear, (100 - width) / 2, 20);
    g2.dispose();
    cb.addTemplate(tp, 0, 0);
    document.close();
  }
}








29.13.Font
29.13.1.Create font
29.13.2.new Font(Font.COURIER, 10, Font.BOLD)
29.13.3.Font.UNDERLINE
29.13.4.Create font from pfm file
29.13.5.Embeded font
29.13.6..afm font
29.13.7.TrueType font
29.13.8..otf font
29.13.9.Font Metrics
29.13.10.Embeded TrueType Font
29.13.11.All kinds of fonts
29.13.12.Get font name
29.13.13.Not Embedded font
29.13.14.Font supporting Unicode
29.13.15.Japanese font
29.13.16.Korea font
29.13.17.Right To Left Example
29.13.18.BaseFont.createFont(BaseFont.HELVETICA,BaseFont.WINANSI, BaseFont.NOT_EMBEDDED)
29.13.19.Use truetype font to draw unicode string
29.13.20.Use DefaultFontMapper