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(); } }