Skip to main content
Skip table of contents

iText in Action Chapter 11: Choosing the right font

These examples were written in the context of Chapter 11 of the book "iText in Action - Second Edition".


fonttypes

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;

public class FontTypes {

    /** The resulting PDF file. */
    public static String RESULT
        = "results/part3/chapter11/font_types.pdf";
    /** Some text. */
    public static String TEXT
        = "quick brown fox jumps over the lazy dog\nQUICK BROWN FOX JUMPS OVER THE LAZY DOG";
    
    /** Paths to and encodings of fonts we're going to use in this example */
    public static String[][] FONTS = {
        {BaseFont.HELVETICA, BaseFont.WINANSI},
        {"resources/fonts/cmr10.afm", BaseFont.WINANSI},
        {"resources/fonts/cmr10.pfm", BaseFont.WINANSI},
        //{"c:/windows/fonts/ARBLI__.TTF", BaseFont.WINANSI},
        {"c:/windows/fonts/arial.ttf", BaseFont.WINANSI},
        {"c:/windows/fonts/arial.ttf", BaseFont.IDENTITY_H},
        {"resources/fonts/Puritan2.otf", BaseFont.WINANSI},
        {"c:/windows/fonts/msgothic.ttc,0", BaseFont.IDENTITY_H},
        {"KozMinPro-Regular", "UniJIS-UCS2-H"}
    };

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
    	// step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        BaseFont bf;
        Font font;
        for (int i = 0; i < FONTS.length; i++) {
            bf = BaseFont.createFont(FONTS[i][0], FONTS[i][1], BaseFont.EMBEDDED);
            document.add(new Paragraph(
                    String.format("Font file: %s with encoding %s", FONTS[i][0], FONTS[i][1])));
            document.add(new Paragraph(
                    String.format("iText class: %s", bf.getClass().getName())));
            font = new Font(bf, 12);
            document.add(new Paragraph(TEXT, font));
            document.add(new LineSeparator(0.5f, 100, null, 0, -5));
        }
        // step 5
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new FontTypes().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.draw;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class FontTypes : IWriter {
// ===========================================================================
    /** Some text. */
    public const string TEXT
        = "quick brown fox jumps over the lazy dog\nQUICK BROWN FOX JUMPS OVER THE LAZY DOG";
    
/** Paths to and encodings of fonts we're going to use in this example;
 * you may have to comment out some of the fonts to run example 
*/
    public readonly string[][] FONTS = {
      new string[] {BaseFont.HELVETICA, BaseFont.WINANSI},
      new string[] {Path.Combine(Utility.ResourceFonts, "cmr10.afm"), BaseFont.WINANSI},
      new string[] {Path.Combine(Utility.ResourceFonts, "cmr10.pfm"), BaseFont.WINANSI},
      //new string[] {"c:/windows/fonts/ARBLI__.TTF", BaseFont.WINANSI},
      new string[] {"c:/windows/fonts/arial.ttf", BaseFont.WINANSI},
      new string[] {"c:/windows/fonts/arial.ttf", BaseFont.IDENTITY_H},
      new string[] {Path.Combine(Utility.ResourceFonts, "Puritan2.otf"), BaseFont.WINANSI},
      new string[] {"c:/windows/fonts/msgothic.ttc,0", BaseFont.IDENTITY_H},
      new string[] {"KozMinPro-Regular", "UniJIS-UCS2-H"}
    };
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf;
        Font font;
        for (int i = 0; i < FONTS.Length; i++) {
          bf = BaseFont.CreateFont(FONTS[i][0], FONTS[i][1], BaseFont.EMBEDDED);
          document.Add(new Paragraph(String.Format("Font file: {0} with encoding {1}", 
            FONTS[i][0], FONTS[i][1]
          )));
          document.Add(new Paragraph(
            String.Format("iText class: {0}", bf.GetType().ToString()
          )));
          font = new Font(bf, 12);
          document.Add(new Paragraph(TEXT, font));
          document.Add(new LineSeparator(0.5f, 100, null, 0, -5));
        }
      }
    }
// ===========================================================================
  }
}


ttcexample

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class TTCExample {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/ttc_example.pdf";
    /** The path to the font. */
    public static final String FONT = "c:/windows/fonts/msgothic.ttc";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3: we open the document
        document.open();
        // step 4

        BaseFont bf;
        Font font;
        String[] names = BaseFont.enumerateTTCNames(FONT);
        for (int i = 0; i < names.length; i++) {
            bf = BaseFont.createFont(String.format("%s,%s", FONT, i),
                BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            font = new Font(bf, 12);
            document.add(new Paragraph("font " + i + ": " + names[i], font));
            document.add(new Paragraph("Rash\u00f4mon", font));
            document.add(new Paragraph("Directed by Akira Kurosawa", font));
            document.add(new Paragraph("\u7f85\u751f\u9580", font));
            document.add(Chunk.NEWLINE);
        }
        // step 5: we close the document
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new TTCExample().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class TTCExample : IWriter {
// ===========================================================================
  /** The path to the font. */
    public const string FONT = "c:/windows/fonts/msgothic.ttc";
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf;
        Font font;
        String[] names = BaseFont.EnumerateTTCNames(FONT);
        for (int i = 0; i < names.Length; i++) {
          bf = BaseFont.CreateFont(
            String.Format("{0}, {1}", FONT, i),
            BaseFont.IDENTITY_H, BaseFont.EMBEDDED
          );
          font = new Font(bf, 12);
          document.Add(new Paragraph("font " + i + ": " + names[i], font));
          document.Add(new Paragraph("Rash\u00f4mon", font));
          document.Add(new Paragraph("Directed by Akira Kurosawa", font));
          document.Add(new Paragraph("\u7f85\u751f\u9580", font));
          document.Add(Chunk.NEWLINE);
        }
      }
    }
// ===========================================================================
  }
}


encodingnames

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class EncodingNames {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/font_encodings.pdf";
    /** The path to the font. */
    public static final String[] FONT = {
        "c:/windows/fonts/ARBLI__.TTF",
        "resources/fonts/Puritan2.otf",
        "c:/windows/fonts/arialbd.ttf"
    };
    

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document(new Rectangle(350, 842));
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        showEncodings(document, FONT[0]);
        showEncodings(document, FONT[1]);
        document.newPage();
        showEncodings(document, FONT[2]);
        // step 5
        document.close();
    }
    
    /**
     * Writes the available encodings of a font to the document.
     * @param document the document to which the encodings have to be written
     * @param font     the font
     * @throws DocumentException
     * @throws IOException
     */
    public void showEncodings(Document document, String font) throws DocumentException, IOException {
        BaseFont bf = BaseFont.createFont(font, BaseFont.WINANSI, BaseFont.EMBEDDED);
        document.add(new Paragraph("PostScript name: " + bf.getPostscriptFontName()));
        document.add(new Paragraph("Available code pages:"));
        String[] encoding = bf.getCodePagesSupported();
        for (int i = 0; i < encoding.length; i++) {
            document.add(new Paragraph("encoding[" + i + "] = " + encoding[i]));
        }
        document.add(Chunk.NEWLINE);
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args)
        throws IOException, DocumentException {
        new EncodingNames().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class EncodingNames : IWriter {
// ===========================================================================
/** The path to the font. 
 *  you may have to comment out some of the fonts to run example 
*/
    public readonly string[] FONT = {
      //"c:/windows/fonts/ARBLI__.TTF",
      Path.Combine(Utility.ResourceFonts, "Puritan2.otf"),
      "c:/windows/fonts/arialbd.ttf"
    };
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        for (int i = 0; i < FONT.Length; ++i) {
          BaseFont bf = BaseFont.CreateFont(FONT[i],  BaseFont.WINANSI, BaseFont.EMBEDDED);
          document.Add(new Paragraph("PostScript name: " + bf.PostscriptFontName));
          document.Add(new Paragraph("Available code pages:"));
          string[] encoding = bf.CodePagesSupported;
          for (int j = 0; j < encoding.Length; j++) {
            document.Add(new Paragraph("encoding[" + j + "] = " + encoding[j]));
          }
          document.Add(Chunk.NEWLINE);        
        }
      }
    }
// ===========================================================================
  }
}


encodingexample

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class EncodingExample {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/encoding_example.pdf";
    /** The path to the font. */
    public static final String FONT
        = "c:/windows/fonts/arialbd.ttf";
    /** Movie information. */
    public static final String[][] MOVIES = {
        {
            "Cp1252",
            "A Very long Engagement (France)",
            "directed by Jean-Pierre Jeunet",
            "Un long dimanche de fian\u00e7ailles"
        },
        {
            "Cp1250",
            "No Man's Land (Bosnia-Herzegovina)",
            "Directed by Danis Tanovic",
            "Nikogar\u0161nja zemlja"
        },
        {
            "Cp1251",
            "You I Love (Russia)",
            "directed by Olga Stolpovskaja and Dmitry Troitsky",
            "\u042f \u043b\u044e\u0431\u043b\u044e \u0442\u0435\u0431\u044f"
        },
        {
            "Cp1253",
            "Brides (Greece)",
            "directed by Pantelis Voulgaris",
            "\u039d\u03cd\u03c6\u03b5\u03c2"
        }
    };
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        BaseFont bf;
        for (int i = 0; i < 4; i++) {
            bf = BaseFont.createFont(FONT, MOVIES[i][0], BaseFont.EMBEDDED);
            document.add(new Paragraph("Font: " + bf.getPostscriptFontName()
                    + " with encoding: " + bf.getEncoding()));
            document.add(new Paragraph(MOVIES[i][1]));
            document.add(new Paragraph(MOVIES[i][2]));
            document.add(new Paragraph(MOVIES[i][3], new Font(bf, 12)));
            document.add(Chunk.NEWLINE);
        }
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args)
        throws IOException, DocumentException {
        new EncodingExample().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class EncodingExample : IWriter {
// ===========================================================================
    /** The path to the font. */
    public const string FONT = "c:/windows/fonts/arialbd.ttf";
    /** Movie information. */
    public readonly string[][] MOVIES = {
      new string[] {
        "Cp1252",
        "A Very long Engagement (France)",
        "directed by Jean-Pierre Jeunet",
        "Un long dimanche de fian\u00e7ailles"
      },
      new string[] {
        "Cp1250",
        "No Man's Land (Bosnia-Herzegovina)",
        "Directed by Danis Tanovic",
        "Nikogar\u0161nja zemlja"
      },
      new string[] {
        "Cp1251",
        "You I Love (Russia)",
        "directed by Olga Stolpovskaja and Dmitry Troitsky",
        "\u042f \u043b\u044e\u0431\u043b\u044e \u0442\u0435\u0431\u044f"
      },
      new string[] {
        "Cp1253",
        "Brides (Greece)",
        "directed by Pantelis Voulgaris",
        "\u039d\u03cd\u03c6\u03b5\u03c2"
      }
    };
// ---------------------------------------------------------------------------
    public virtual void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf;
        for (int i = 0; i < 4; i++) {
          bf = BaseFont.CreateFont(FONT, MOVIES[i][0], BaseFont.EMBEDDED);
          document.Add(new Paragraph(
            "Font: " + bf.PostscriptFontName
            + " with encoding: " + bf.Encoding
          ));
          document.Add(new Paragraph(MOVIES[i][1]));
          document.Add(new Paragraph(MOVIES[i][2]));
          document.Add(new Paragraph(MOVIES[i][3], new Font(bf, 12)));
          document.Add(Chunk.NEWLINE);
        } 
      }
    }
// ===========================================================================
  }
}


unicodeexample

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class UnicodeExample extends EncodingExample {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/unicode_example.pdf";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3: we open the document
        document.open();
        // step 4
        BaseFont bf;
        for (int i = 0; i < 4; i++) {
            bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            document.add(new Paragraph("Font: " + bf.getPostscriptFontName()
                    + " with encoding: " + bf.getEncoding()));
            document.add(new Paragraph(MOVIES[i][1]));
            document.add(new Paragraph(MOVIES[i][2]));
            document.add(new Paragraph(MOVIES[i][3], new Font(bf, 12)));
            document.add(Chunk.NEWLINE);
        }
        // step 5: we close the document
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args)
        throws IOException, DocumentException {
        new UnicodeExample().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class UnicodeExample : EncodingExample {
// ===========================================================================
    public override void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf;
        for (int i = 0; i < 4; i++) {
          bf = BaseFont.CreateFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
          document.Add(new Paragraph(
            "Font: " + bf.PostscriptFontName
            + " with encoding: " + bf.Encoding
          ));
          document.Add(new Paragraph(MOVIES[i][1]));
          document.Add(new Paragraph(MOVIES[i][2]));
          document.Add(new Paragraph(MOVIES[i][3], new Font(bf, 12)));
          document.Add(Chunk.NEWLINE);
        } 
      }
    }
// ===========================================================================
  }
}


fontfileandsizes

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class FontFileAndSizes {

    /** The names of the resulting PDF files. */
    public static final String[] RESULT = {
        "results/part3/chapter11/font_not_embedded.pdf",
        "results/part3/chapter11/font_embedded.pdf",
        "results/part3/chapter11/font_embedded_less_glyphs.pdf",
        "results/part3/chapter11/font_compressed.pdf",
        "results/part3/chapter11/font_full.pdf"
    };
    /** The path to the font. */
    public static final String FONT = "c:/windows/fonts/arial.ttf";
    /** Some text. */
    public static String TEXT
        = "quick brown fox jumps over the lazy dog";
    /** Some text. */
    public static String OOOO
        = "ooooo ooooo ooo ooooo oooo ooo oooo ooo";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename, BaseFont bf, String text)
        throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        document.add(new Paragraph(text, new Font(bf, 12)));
        // step 5
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        FontFileAndSizes ffs = new FontFileAndSizes();
        BaseFont bf;
        bf = BaseFont.createFont(FONT, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
        ffs.createPdf(RESULT[0], bf, TEXT);
        bf = BaseFont.createFont(FONT, BaseFont.WINANSI, BaseFont.EMBEDDED);
        ffs.createPdf(RESULT[1], bf, TEXT);
        ffs.createPdf(RESULT[2], bf, OOOO);
        bf = BaseFont.createFont(FONT, BaseFont.WINANSI, BaseFont.EMBEDDED);
        bf.setCompressionLevel(9);
        ffs.createPdf(RESULT[3], bf, TEXT);
        bf = BaseFont.createFont(FONT, BaseFont.WINANSI, BaseFont.EMBEDDED);
        bf.setSubset(false);
        ffs.createPdf(RESULT[4], bf, TEXT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;

using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class FontFileAndSizes : IWriter {
// ===========================================================================
    /** The names of the resulting PDF files. */
    public string[] RESULT {
      get { return new string[] {
          "font_not_embedded.pdf",
          "font_embedded.pdf",
          "font_embedded_less_glyphs.pdf",
          "font_compressed.pdf",
          "font_full.pdf"
        };
      }
    }
    /** The path to the font. */
    public const string FONT = "c:/windows/fonts/arial.ttf";
    /** Some text. */
    public const string TEXT
        = "quick brown fox jumps over the lazy dog";
    /** Some text. */
    public const string OOOO
        = "ooooo ooooo ooo ooooo oooo ooo oooo ooo";
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        FontFileAndSizes ffs = new FontFileAndSizes();
        BaseFont bf;
        bf = BaseFont.CreateFont(FONT, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
        zip.AddEntry(RESULT[0], ffs.CreatePdf(bf, TEXT));
        bf = BaseFont.CreateFont(FONT, BaseFont.WINANSI, BaseFont.EMBEDDED);
        zip.AddEntry(RESULT[1], ffs.CreatePdf(bf, TEXT));
        zip.AddEntry(RESULT[2], ffs.CreatePdf(bf, OOOO));
        bf = BaseFont.CreateFont(FONT, BaseFont.WINANSI, BaseFont.EMBEDDED);
        bf.CompressionLevel = 9;
        zip.AddEntry(RESULT[3], ffs.CreatePdf(bf, TEXT));
        bf = BaseFont.CreateFont(FONT, BaseFont.WINANSI, BaseFont.EMBEDDED);
        bf.Subset = false;
        zip.AddEntry(RESULT[4], ffs.CreatePdf(bf, TEXT)); 
        zip.Save(stream);             
      }
    }
// ---------------------------------------------------------------------------    
    /**
     * Creates a PDF document.
     */
    public byte[] CreatePdf(BaseFont bf, String text) {
      using (MemoryStream ms = new MemoryStream()) {
        using (Document document = new Document()) {
          PdfWriter.GetInstance(document, ms);
          document.Open();
          document.Add(new Paragraph(text, new Font(bf, 12)));
        }
        return ms.ToArray();
      }
    }    
// ===========================================================================
  }
}


type3example

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.Type3Font;

public class Type3Example {
    
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/type3_example.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        Type3Font t3 = new Type3Font(writer, true);
        PdfContentByte d = t3.defineGlyph('D', 600, 0, 0, 600, 700);
        d.setColorStroke(new BaseColor(0xFF, 0x00, 0x00));
        d.setColorFill(new GrayColor(0.7f));
        d.setLineWidth(100);
        d.moveTo(5, 5);
        d.lineTo(300, 695);
        d.lineTo(595, 5);
        d.closePathFillStroke();
        PdfContentByte s = t3.defineGlyph('S', 600, 0, 0, 600, 700);
        s.setColorStroke(new BaseColor(0x00, 0x80, 0x80));
        s.setLineWidth(100);
        s.moveTo(595,5);
        s.lineTo(5, 5);
        s.lineTo(300, 350);
        s.lineTo(5, 695);
        s.lineTo(595, 695);
        s.stroke();
        Font f = new Font(t3, 12);
        Paragraph p = new Paragraph();
        p.add("This is a String with a Type3 font that contains a fancy Delta (");
        p.add(new Chunk("D", f));
        p.add(") and a custom Sigma (");
        p.add(new Chunk("S", f));
        p.add(").");
        document.add(p);
        // step 5: we close the document
        document.close();
    }
    
    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Type3Example().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class Type3Example : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        Type3Font t3 = new Type3Font(writer, true);
        PdfContentByte d = t3.DefineGlyph('D', 600, 0, 0, 600, 700);
        d.SetColorStroke(new BaseColor(0xFF, 0x00, 0x00));
        d.SetColorFill(new GrayColor(0.7f));
        d.SetLineWidth(100);
        d.MoveTo(5, 5);
        d.LineTo(300, 695);
        d.LineTo(595, 5);
        d.ClosePathFillStroke();
        PdfContentByte s = t3.DefineGlyph('S', 600, 0, 0, 600, 700);
        s.SetColorStroke(new BaseColor(0x00, 0x80, 0x80));
        s.SetLineWidth(100);
        s.MoveTo(595,5);
        s.LineTo(5, 5);
        s.LineTo(300, 350);
        s.LineTo(5, 695);
        s.LineTo(595, 695);
        s.Stroke();
        Font f = new Font(t3, 12);
        Paragraph p = new Paragraph();
        p.Add("This is a String with a Type3 font that contains a fancy Delta (");
        p.Add(new Chunk("D", f));
        p.Add(") and a custom Sigma (");
        p.Add(new Chunk("S", f));
        p.Add(").");
        document.Add(p);        
      }
    }
// ===========================================================================
  }
}


cjkexample

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class CJKExample {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/cjk_example.pdf";
    /** Movies, their director and original title */
    public static final String[][] MOVIES = {
        {
            "STSong-Light", "UniGB-UCS2-H",
            "Movie title: House of The Flying Daggers (China)",
            "directed by Zhang Yimou",
            "\u5341\u950a\u57cb\u4f0f"
        },
        {
            "KozMinPro-Regular", "UniJIS-UCS2-H",
            "Movie title: Nobody Knows (Japan)",
            "directed by Hirokazu Koreeda",
            "\u8ab0\u3082\u77e5\u3089\u306a\u3044"
        },
        {
            "HYGoThic-Medium", "UniKS-UCS2-H",
            "Movie title: '3-Iron' aka 'Bin-jip' (South-Korea)",
            "directed by Kim Ki-Duk",
            "\ube48\uc9d1"
        }
    };
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        BaseFont bf;
        Font font;
        
        for (int i = 0; i < 3; i++) {
            bf = BaseFont.createFont(MOVIES[i][0], MOVIES[i][1], BaseFont.NOT_EMBEDDED);
            font = new Font(bf, 12);
            document.add(new Paragraph(bf.getPostscriptFontName(), font));
            for (int j = 2; j < 5; j++)
                document.add(new Paragraph(MOVIES[i][j], font));
            document.add(Chunk.NEWLINE);
        }

        
        // step 5
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new CJKExample().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class CJKExample : IWriter {
// ===========================================================================
    /** Movies, their director and original title */
    public readonly string[][] MOVIES = {
      new string[] {
        "STSong-Light", "UniGB-UCS2-H",
        "Movie title: House of The Flying Daggers (China)",
        "directed by Zhang Yimou",
        "\u5341\u950a\u57cb\u4f0f"
      },
      new string[] {
        "KozMinPro-Regular", "UniJIS-UCS2-H",
        "Movie title: Nobody Knows (Japan)",
        "directed by Hirokazu Koreeda",
        "\u8ab0\u3082\u77e5\u3089\u306a\u3044"
      },
      new string[] {
        "HYGoThic-Medium", "UniKS-UCS2-H",
        "Movie title: '3-Iron' aka 'Bin-jip' (South-Korea)",
        "directed by Kim Ki-Duk",
        "\ube48\uc9d1"
      }
    };
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf;
        Font font;
        for (int i = 0; i < 3; i++) {
          bf = BaseFont.CreateFont(
            MOVIES[i][0], MOVIES[i][1], BaseFont.NOT_EMBEDDED
          );
          font = new Font(bf, 12);
          document.Add(new Paragraph(bf.PostscriptFontName, font));
          for (int j = 2; j < 5; j++) {
            document.Add(new Paragraph(MOVIES[i][j], font));
          }
          document.Add(Chunk.NEWLINE);
        }        
      }
    }
// ===========================================================================
  }
}


verticaltextexample1

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.VerticalText;

public class VerticalTextExample1 {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/vertical_text_1.pdf";
    /** A Japanese String. */
    public static final String MOVIE = "\u4e03\u4eba\u306e\u4f8d";
    /** The facts. */
    public static final String TEXT1
       = "You embarrass me. You're overestimating me. "
       + "Listen, I'm not a man with any special skill, "
       + "but I've had plenty of experience in battles; losing battles, all of them.";
    /** The conclusion. */
    public static final String TEXT2
       = "In short, that's all I am. Drop such an idea for your own good.";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document(new Rectangle(420, 600));
        // step 2
        PdfWriter writer
            = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3: we open the document
        document.open();
        // step 4
        BaseFont bf = BaseFont.createFont(
            "KozMinPro-Regular", "UniJIS-UCS2-V", BaseFont.NOT_EMBEDDED);
        Font font = new Font(bf, 20);
        VerticalText vt = new VerticalText(writer.getDirectContent());
        vt.setVerticalLayout(390, 570, 540, 12, 30);
        vt.addText(new Chunk(MOVIE, font));
        vt.go();
        vt.addText(new Phrase(TEXT1, font));
        vt.go();
        vt.setAlignment(Element.ALIGN_RIGHT);
        vt.addText(new Phrase(TEXT2, font));
        vt.go();
        // step 5: we close the document
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new VerticalTextExample1().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class VerticalTextExample1 : IWriter {
// ===========================================================================
    /** A Japanese String. */
    public const string MOVIE = "\u4e03\u4eba\u306e\u4f8d";
    /** The facts. */
    public const string TEXT1
    = "You embarrass me. You're overestimating me. "
    + "Listen, I'm not a man with any special skill, "
    + "but I've had plenty of experience in battles; losing battles, all of them.";
    /** The conclusion. */
    public const string TEXT2
    = "In short, that's all I am. Drop such an idea for your own good.";
// ---------------------------------------------------------------------------
    public virtual void Write(Stream stream) {
      // step 1
      using (Document document = new Document(new Rectangle(420, 600))) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf = BaseFont.CreateFont(
          "KozMinPro-Regular", "UniJIS-UCS2-V", BaseFont.NOT_EMBEDDED
        );
        Font font = new Font(bf, 20);
        VerticalText vt = new VerticalText(writer.DirectContent);
        vt.SetVerticalLayout(390, 570, 540, 12, 30);
        vt.AddText(new Chunk(MOVIE, font));
        vt.Go();
        vt.AddText(new Phrase(TEXT1, font));
        vt.Go();
        vt.Alignment = Element.ALIGN_RIGHT;
        vt.AddText(new Phrase(TEXT2, font));
        vt.Go();
      }
    }
// ===========================================================================
  }
}


verticaltextexample2

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.VerticalText;

public class VerticalTextExample2 extends VerticalTextExample1 {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/vertical_text_2.pdf";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document(new Rectangle(420, 600));
        // step 2
        PdfWriter writer
            = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3: we open the document
        document.open();
        // step 4
        BaseFont bf = BaseFont.createFont(
            "KozMinPro-Regular", "Identity-V", BaseFont.NOT_EMBEDDED);
        Font font = new Font(bf, 20);
        VerticalText vt = new VerticalText(writer.getDirectContent());
        vt.setVerticalLayout(390, 570, 540, 12, 30);
        font = new Font(bf, 20);
        vt.addText(new Phrase(convertCIDs(TEXT1), font));
        vt.go();
        vt.setAlignment(Element.ALIGN_RIGHT);
        vt.addText(new Phrase(convertCIDs(TEXT2), font));
        vt.go();
        // step 5: we close the document
        document.close();
    }

    /**
     * Converts the CIDs of the horizontal characters of a String
     * into a String with vertical characters.
     * @param text The String with the horizontal characters
     * @return A String with vertical characters
     */
    public String convertCIDs(String text) {
        char cid[] = text.toCharArray();
        for (int k = 0; k < cid.length; ++k) {
            char c = cid[k];
            if (c == '\n')
                cid[k] = '\uff00';
            else
                cid[k] = (char) (c - ' ' + 8720);
        }
        return new String(cid);
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new VerticalTextExample2().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class VerticalTextExample2 : VerticalTextExample1 {
// ===========================================================================
    public override void Write(Stream stream) {
      // step 1
      using (Document document = new Document(new Rectangle(420, 600))) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf = BaseFont.CreateFont(
          "KozMinPro-Regular", "Identity-V", BaseFont.NOT_EMBEDDED
        );
        Font font = new Font(bf, 20);
        VerticalText vt = new VerticalText(writer.DirectContent);
        vt.SetVerticalLayout(390, 570, 540, 12, 30);
        font = new Font(bf, 20);
        vt.AddText(new Phrase(ConvertCIDs(TEXT1), font));
        vt.Go();
        vt.Alignment = Element.ALIGN_RIGHT;
        vt.AddText(new Phrase(ConvertCIDs(TEXT2), font));
        vt.Go();
      }
    }
// ---------------------------------------------------------------------------
/**
 * Converts the CIDs of the horizontal characters of a String
 * into a String with vertical characters.
 * @param text The String with the horizontal characters
 * @return A String with vertical characters
 */
    public string ConvertCIDs(string text) {
      char[] cid = text.ToCharArray();
      for (int k = 0; k < cid.Length; ++k) {
        char c = cid[k];
        cid[k] = c == '\n' ? '\uff00' : (char) (c - ' ' + 8720);
      }
      return new String(cid);
    }
// ===========================================================================
  }
}


righttoleftexample

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfWriter;

public class RightToLeftExample {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/right_to_left.pdf";
    /** A movie title. */
    public static final String MOVIE
        = "\u05d4\u05d0\u05e1\u05d5\u05e0\u05d5\u05ea \u05e9\u05dc \u05e0\u05d9\u05e0\u05d4";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document(PageSize.A4);
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        BaseFont bf = BaseFont.createFont(
            "c:/windows/fonts/arial.ttf", BaseFont.IDENTITY_H, true);
        Font font = new Font(bf, 14);
        document.add(new Paragraph("Movie title: Nina's Tragedies"));
        document.add(new Paragraph("directed by Savi Gabizon"));
        ColumnText column = new ColumnText(writer.getDirectContent());
        column.setSimpleColumn(36, 770, 569, 36);
        column.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
        column.addElement(new Paragraph(MOVIE, font));
        column.go();
        // step 5
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new RightToLeftExample().createPdf(RESULT);
    }

}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class RightToLeftExample : IWriter {
// ===========================================================================
    /** A movie title. */
    public const string MOVIE =
    "\u05d4\u05d0\u05e1\u05d5\u05e0\u05d5\u05ea \u05e9\u05dc \u05e0\u05d9\u05e0\u05d4";
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document(PageSize.A4)) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf = BaseFont.CreateFont(
          "c:/windows/fonts/arial.ttf", BaseFont.IDENTITY_H, true
        );
        Font font = new Font(bf, 14);
        document.Add(new Paragraph("Movie title: Nina's Tragedies"));
        document.Add(new Paragraph("directed by Savi Gabizon"));
        ColumnText column = new ColumnText(writer.DirectContent);
        column.SetSimpleColumn(36, 770, 569, 36);
        column.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
        column.AddElement(new Paragraph(MOVIE, font));
        column.Go();
      }
    }
// ===========================================================================
  }
}


saypeace

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * This example was written by Bruno Lowagie. It is part of the book 'iText in
 * Action' by Manning Publications. 
 * ISBN: 1932394796
 * http://www.1t3xt.com/docs/book.php 
 * http://www.manning.com/lowagie/
 */

public class SayPeace extends DefaultHandler {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/say_peace.pdf";
    /** The XML file with the text. */
    public static final String RESOURCE
        = "resources/xml/say_peace.xml";
    
    /** The font that is used for the peace message. */
    public Font f;

    /** The document to which we are going to add our message. */
    protected Document document;

    /** The StringBuffer that holds the characters. */
    protected StringBuffer buf = new StringBuffer();
    
    /** The table that holds the text. */
    protected PdfPTable table;
    
    /** The current cell. */
    protected PdfPCell cell;

    /**
     * @see org.xml.sax.ContentHandler#startElement(java.lang.String,
     *      java.lang.String, java.lang.String, org.xml.sax.Attributes)
     */
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        if ("message".equals(qName)) {
            buf = new StringBuffer();
            cell = new PdfPCell();
            cell.setBorder(PdfPCell.NO_BORDER);
            if ("RTL".equals(attributes.getValue("direction"))) {
                cell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
            }
        }
        else if ("pace".equals(qName)) {
            table = new PdfPTable(1);
            table.setWidthPercentage(100);
        }
    }

    /**
     * @see org.xml.sax.ContentHandler#endElement(java.lang.String,
     *      java.lang.String, java.lang.String)
     */
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if ("big".equals(qName)) {
            Chunk bold = new Chunk(strip(buf), f);
            bold.setTextRenderMode(
                    PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, 0.5f,
                    GrayColor.GRAYBLACK);
            Paragraph p = new Paragraph(bold);
            p.setAlignment(Element.ALIGN_LEFT);
            cell.addElement(p);
            buf = new StringBuffer();
        }
        else if ("message".equals(qName)) {
            Paragraph p = new Paragraph(strip(buf), f);
            p.setAlignment(Element.ALIGN_LEFT);
            cell.addElement(p);
            table.addCell(cell);
            buf = new StringBuffer();
        }
        else if ("pace".equals(qName)) {
            try {
                document.add(table);
            } catch (DocumentException e) {
                throw new ExceptionConverter(e);
            }
        }
    }

    /**
     * @see org.xml.sax.ContentHandler#characters(char[], int, int)
     */
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        buf.append(ch, start, length);
    }

    /**
     * Replaces all the newline characters by a space.
     * 
     * @param buf
     *            the original StringBuffer
     * @return a String without newlines
     */
    protected String strip(StringBuffer buf) {
        int pos;
        while ((pos = buf.indexOf("\n")) != -1)
            buf.replace(pos, pos + 1, " ");
        while (buf.charAt(0) == ' ')
            buf.deleteCharAt(0);
        return buf.toString();
    }

    /**
     * Creates the handler to read the peace message.
     * 
     * @param document
     * @param is
     * @throws FactoryConfigurationError
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws FactoryConfigurationError
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws DocumentException
     */
    public SayPeace(Document document, InputSource is)
            throws ParserConfigurationException, SAXException,
            FactoryConfigurationError, DocumentException, IOException {
        this.document = document;
        f = new Font(BaseFont.createFont("c:/windows/fonts/arialuni.ttf",
                BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        parser.parse(is, this);
    }

    /**
     * Generates a PDF with a Peace message in English, Arabic and Hebrew.
     * 
     * @param args no arguments needed
     */
    public static void main(String[] args) {
        // step 1:
        Document document = new Document(PageSize.A4);
        try {
            // step 2:
            PdfWriter.getInstance(document, new FileOutputStream(RESULT));
            // step 3:
            document.open();
            // step 4:
            new SayPeace(document,
                new InputSource(new FileInputStream(RESOURCE)));
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        // step 5: we close the document
        document.close();
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class SayPeace : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const String RESULT = "say_peace.pdf";
    /** The XML file with the text. */
    public static string RESOURCE = Path.Combine(
      Utility.ResourceXml, "say_peace.xml"
    );
    /** The font that is used for the peace message. */
    public Font f;
    /** The document to which we are going to add our message. */
    protected Document document;

    /** The StringBuilder that holds the characters. */
    protected StringBuilder buf = new StringBuilder();
    
    /** The table that holds the text. */
    protected PdfPTable table;
    
    /** The current cell. */
    protected PdfPCell cell; 
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        zip.AddFile(RESOURCE, "");
        
        using (MemoryStream ms = new MemoryStream()) {
          // step 1
          using (document = new Document()) {
            // step 2
            PdfWriter.GetInstance(document, ms);
            // step 3
            document.Open();
            // step 4
            f = new Font(BaseFont.CreateFont("c:/windows/fonts/arialuni.ttf",
              BaseFont.IDENTITY_H, BaseFont.EMBEDDED
            ));
            using (XmlReader xr = XmlReader.Create(RESOURCE)) {
              table = new PdfPTable(1);
              xr.MoveToContent();
              while (xr.Read()) {
                switch (xr.NodeType) {
                  case XmlNodeType.Element:
                    StartElement(xr);
                    break;
                  case XmlNodeType.Text:
                    buf.Append(xr.Value.Trim());
                    break;
                  case XmlNodeType.EndElement:
                    EndElement(xr.Name);
                    break;
                }
              }
            }
          }
          zip.AddEntry(RESULT, ms.ToArray()); 
        }
        zip.Save(stream);             
      }
    }       
// ---------------------------------------------------------------------------
    public void StartElement(XmlReader xr) {
      string name =  xr.Name;
      if ("message".Equals(name)) {
        buf = new StringBuilder();
        cell = new PdfPCell();
        cell.Border = PdfPCell.NO_BORDER;
        string direction = xr.GetAttribute("direction") != null
          ? xr.GetAttribute("direction")
          : ""
        ;
        if ("RTL".Equals(direction)) {
          cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
        }
      }
      else if ("pace".Equals(name)) {
        table = new PdfPTable(1);
        table.WidthPercentage = 100;
      }
    }
// ---------------------------------------------------------------------------
    public void EndElement(string name) {
      if ("big".Equals(name)) {
        Chunk bold = new Chunk(Strip(buf), f);
        bold.SetTextRenderMode(
          PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, 0.5f,
          GrayColor.GRAYBLACK
        );
        Paragraph p = new Paragraph(bold);
        p.Alignment = Element.ALIGN_LEFT;
        cell.AddElement(p);
        buf = new StringBuilder();
      }
      else if ("message".Equals(name)) {
        Paragraph p = new Paragraph(Strip(buf), f);
        p.Alignment = Element.ALIGN_LEFT;
        cell.AddElement(p);
        table.AddCell(cell);
        buf = new StringBuilder();
      }
      else if ("pace".Equals(name)) {
        document.Add(table);
      }
    }
// ---------------------------------------------------------------------------    
  /**
   * Replaces all the newline characters by a space.
   * 
   * @param buf the original StringBuffer
   * @return a String without newlines
   */
    protected string Strip(StringBuilder buf) {
      buf.Replace("\n", " ");
      return buf.ToString();
    }    
// ===========================================================================
  }
}


diacritics1

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfWriter;

public class Diacritics1 {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/diacritics1.pdf";
    /** A movie title. */
    public static final String MOVIE
        = "\u0e1f\u0e49\u0e32\u0e17\u0e30\u0e25\u0e32\u0e22\u0e42\u0e08\u0e23";
    /** Movie poster */
    public static final String POSTER
        = "resources/posters/0269217.jpg";
    /** Fonts */
    public static final String[] FONTS = {
        "c:/windows/fonts/angsa.ttf",
        "c:/windows/fonts/arialuni.ttf"
    };
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        BaseFont bf;
        Font font;
        Image img = Image.getInstance(POSTER);
        img.scalePercent(50);
        img.setBorderWidth(18f);
        img.setBorder(Image.BOX);
        img.setBorderColor(GrayColor.GRAYWHITE);
        img.setAlignment(Element.ALIGN_LEFT | Image.TEXTWRAP);
        document.add(img);
        document.add(new Paragraph(
            "Movie title: Tears of the Black Tiger (Thailand)"));
        document.add(new Paragraph("directed by Wisit Sasanatieng"));
        for (int i = 0; i < 2; i++) {
            bf = BaseFont.createFont(FONTS[i], BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            document.add(new Paragraph("Font: " + bf.getPostscriptFontName()));
            font = new Font(bf, 20);
            document.add(new Paragraph(MOVIE, font));
        }
        // step 5
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Diacritics1().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class Diacritics1 : IWriter {
// ===========================================================================
    /** A movie title. */
    public const string MOVIE = 
    "\u0e1f\u0e49\u0e32\u0e17\u0e30\u0e25\u0e32\u0e22\u0e42\u0e08\u0e23";
    /** Movie poster */
    public static string POSTER = Path.Combine(
      Utility.ResourcePosters, "0269217.jpg"
    );
    /** Fonts */
    public readonly string[] FONTS = {
      "c:/windows/fonts/angsa.ttf",
      "c:/windows/fonts/arialuni.ttf"
    };
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf;
        Font font;
        Image img = Image.GetInstance(POSTER);
        img.ScalePercent(50);
        img.BorderWidth = 18f;
        img.Border = Image.BOX;
        img.BorderColor = GrayColor.GRAYWHITE;
        img.Alignment = Element.ALIGN_LEFT | Image.TEXTWRAP;
        document.Add(img);
        document.Add(new Paragraph(
          "Movie title: Tears of the Black Tiger (Thailand)"
        ));
        document.Add(new Paragraph("directed by Wisit Sasanatieng"));
        for (int i = 0; i < 2; i++) {
          bf = BaseFont.CreateFont(
            FONTS[i], BaseFont.IDENTITY_H, BaseFont.EMBEDDED
          );
          document.Add(new Paragraph("Font: " + bf.PostscriptFontName));
          font = new Font(bf, 20);
          document.Add(new Paragraph(MOVIE, font));
        }
      }
    }
// ===========================================================================
  }
}


diacritics2

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;


public class Diacritics2 {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/diacritics2.pdf";
    /** A movie title. */
    public static final String MOVIE
        = "Tomten \u00a8ar far till alla barnen";
    /** Fonts */
    public static final String[] FONTS = {
        "c:/windows/fonts/arial.ttf",
        "c:/windows/fonts/cour.ttf"
    };
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        document.add(new Paragraph("Movie title: In Bed With Santa (Sweden)"));
        document.add(new Paragraph("directed by Kjell Sundvall"));
        BaseFont bf = BaseFont.createFont(FONTS[0], BaseFont.CP1252, BaseFont.EMBEDDED);
        Font font = new Font(bf, 12);
        bf.setCharAdvance('\u00a8', -100);
        document.add(new Paragraph(MOVIE, font));
        bf = BaseFont.createFont(FONTS[1], BaseFont.CP1252, BaseFont.EMBEDDED);
        bf.setCharAdvance('\u00a8', 0);
        font = new Font(bf, 12);
        document.add(new Paragraph(MOVIE, font));
        // step 5
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Diacritics2().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class Diacritics2 : IWriter {
// ===========================================================================
    /** A movie title. */
    public const string MOVIE = "Tomten \u00a8ar far till alla barnen";
    /** Fonts */
    public readonly string[] FONTS = {
      "c:/windows/fonts/arial.ttf",
      "c:/windows/fonts/cour.ttf"
    };
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        document.Add(new Paragraph("Movie title: In Bed With Santa (Sweden)"));
        document.Add(new Paragraph("directed by Kjell Sundvall"));
        BaseFont bf = BaseFont.CreateFont(
          FONTS[0], BaseFont.CP1252, BaseFont.EMBEDDED
        );
        Font font = new Font(bf, 12);
        bf.SetCharAdvance('\u00a8', -100);
        document.Add(new Paragraph(MOVIE, font));
        bf = BaseFont.CreateFont(FONTS[1], BaseFont.CP1252, BaseFont.EMBEDDED);
        bf.SetCharAdvance('\u00a8', 0);
        font = new Font(bf, 12);
        document.Add(new Paragraph(MOVIE, font));
      }
    }
// ===========================================================================
  }
}


monospace

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class Monospace {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/monospace.pdf";
    /** A movie title. */
    public static final String MOVIE
        = "Aanrijding in Moscou";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3: we open the document
        document.open();
        // step 4
        BaseFont bf1 = BaseFont.createFont("c:/windows/fonts/arial.ttf",
            BaseFont.CP1252, BaseFont.EMBEDDED);
        Font font1 = new Font(bf1, 12);
        document.add(new Paragraph("Movie title: Moscou, Belgium", font1));
        document.add(new Paragraph("directed by Christophe Van Rompaey", font1));
        document.add(new Paragraph(MOVIE, font1));
        BaseFont bf2 = BaseFont.createFont("c:/windows/fonts/cour.ttf",
            BaseFont.CP1252, BaseFont.EMBEDDED);
        Font font2 = new Font(bf2, 12);
        document.add(new Paragraph(MOVIE, font2));
        BaseFont bf3 = BaseFont.createFont("c:/windows/fonts/arialbd.ttf",
            BaseFont.CP1252, BaseFont.EMBEDDED);
        Font font3 = new Font(bf3, 12);
        int widths[] = bf3.getWidths();
        for (int k = 0; k < widths.length; ++k) {
            if (widths[k] != 0)
                widths[k] = 600;
        }
        bf3.setForceWidthsOutput(true);
        document.add(new Paragraph(MOVIE, font3));
        // step 5: we close the document
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Monospace().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class Monospace : IWriter {
// ===========================================================================
    /** A movie title. */
    public const string MOVIE = "Aanrijding in Moscou";
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf1 = BaseFont.CreateFont(
          "c:/windows/fonts/arial.ttf",
          BaseFont.CP1252, BaseFont.EMBEDDED
        );
        Font font1 = new Font(bf1, 12);
        document.Add(new Paragraph("Movie title: Moscou, Belgium", font1));
        document.Add(new Paragraph(
          "directed by Christophe Van Rompaey", font1
        ));
        document.Add(new Paragraph(MOVIE, font1));
        BaseFont bf2 = BaseFont.CreateFont(
          "c:/windows/fonts/cour.ttf",
          BaseFont.CP1252, BaseFont.EMBEDDED
        );
        Font font2 = new Font(bf2, 12);
        document.Add(new Paragraph(MOVIE, font2));
        BaseFont bf3 = BaseFont.CreateFont(
          "c:/windows/fonts/arialbd.ttf",
          BaseFont.CP1252, BaseFont.EMBEDDED
        );
        Font font3 = new Font(bf3, 12);
        int[] widths = bf3.Widths;
        for (int k = 0; k < widths.Length; ++k) {
          if (widths[k] != 0) widths[k] = 600;
        }
        bf3.ForceWidthsOutput = true;
        document.Add(new Paragraph(MOVIE, font3));
      }
    }
// ===========================================================================
  }
}


extracharspace

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class ExtraCharSpace {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/character_spacing.pdf";
    /** A movie title. */
    public static final String MOVIE
        = "Aanrijding in Moscou";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        BaseFont bf1 = BaseFont.createFont("c:/windows/fonts/arial.ttf",
            BaseFont.CP1252, BaseFont.EMBEDDED);
        Font font1 = new Font(bf1, 12);
        document.add(new Paragraph("Movie title: Moscou, Belgium", font1));
        document.add(new Paragraph("directed by Christophe Van Rompaey", font1));
        Chunk chunk = new Chunk(MOVIE, font1);
        chunk.setCharacterSpacing(10);
        document.add(new Paragraph(chunk));
        // step 5
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new ExtraCharSpace().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class ExtraCharSpace : IWriter {
// ===========================================================================
    /** A movie title. */
    public const string MOVIE = "Aanrijding in Moscou";      
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf1 = BaseFont.CreateFont(
          "c:/windows/fonts/arial.ttf",
          BaseFont.CP1252, BaseFont.EMBEDDED
        );
        Font font1 = new Font(bf1, 12);
        document.Add(new Paragraph("Movie title: Moscou, Belgium", font1));
        document.Add(new Paragraph(
          "directed by Christophe Van Rompaey", font1
        ));
        Chunk chunk = new Chunk(MOVIE, font1);
        chunk.SetCharacterSpacing(10);
        document.Add(new Paragraph(chunk));
      }
    }
// ===========================================================================
  }
}


ligatures1

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class Ligatures1 {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/ligatures_1.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3: we open the document
        document.open();
        // step 4
        BaseFont bf = BaseFont.createFont(
            "c:/windows/fonts/arial.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
        Font font = new Font(bf, 12);
        document.add(new Paragraph("Movie title: Love at First Hiccough (Denmark)", font));
        document.add(new Paragraph("directed by Tomas Villum Jensen", font));
        document.add(new Paragraph("K\u00e6rlighed ved f\u00f8rste hik", font));
        document.add(new Paragraph(ligaturize("Kaerlighed ved f/orste hik"), font));
        // step 5: we close the document
        document.close();
    }

    /**
     * Method that makes the ligatures for the combinations 'a' and 'e'
     * and for '/' and 'o'.
     * @param s a String that may have the combinations ae or /o
     * @return a String where the combinations are replaced by a unicode character
     */
    public String ligaturize(String s) {
        int pos;
        while ((pos = s.indexOf("ae")) > -1) {
            s = s.substring(0, pos) + '\u00e6' + s.substring(pos + 2);
        }
        while ((pos = s.indexOf("/o")) > -1) {
            s = s.substring(0, pos) + '\u00f8' + s.substring(pos + 2);
        }
        return s;
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Ligatures1().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class Ligatures1 : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf = BaseFont.CreateFont(
          "c:/windows/fonts/arial.ttf", BaseFont.CP1252, BaseFont.EMBEDDED
        );
        Font font = new Font(bf, 12);
        document.Add(new Paragraph(
          "Movie title: Love at First Hiccough (Denmark)", font
        ));
        document.Add(new Paragraph("directed by Tomas Villum Jensen", font));
        document.Add(new Paragraph("K\u00e6rlighed ved f\u00f8rste hik", font));
        document.Add(new Paragraph(
          Ligaturize("Kaerlighed ved f/orste hik"), font
        ));
      }
    }
// ---------------------------------------------------------------------------
  /**
   * Method that makes the ligatures for the combinations 'a' and 'e'
   * and for '/' and 'o'.
   * @param s a String that may have the combinations ae or /o
   * @return a String where the combinations are replaced by a unicode character
   */
    public String Ligaturize(string s) {
      int pos;
      //while ((pos = s.IndexOf("ae")) > -1) {
      //  s = s.Substring(0, pos) + '\u00e6' + s.Substring(pos + 2);
      //}
      while ((pos = s.IndexOf("/o")) > -1) {
        s = s.Substring(0, pos) + "\u00f8" + s.Substring(pos + 2);
      }
      return s;
    }    
// ===========================================================================
  }
}


ligatures2

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfWriter;

public class Ligatures2 {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/ligatures_2.pdf";
    /** Correct movie title. */
    public static final String MOVIE
        = "\u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628";
    /** Correct movie title. */
    public static final String MOVIE_WITH_SPACES
        = "\u0644 \u0648 \u0631 \u0627 \u0646 \u0633   \u0627 \u0644 \u0639 \u0631 \u0628";
    
    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        BaseFont bf = BaseFont.createFont(
            "c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font font = new Font(bf, 20);
        document.add(new Paragraph("Movie title: Lawrence of Arabia (UK)"));
        document.add(new Paragraph("directed by David Lean"));
        document.add(new Paragraph("Wrong: " + MOVIE, font));
        ColumnText column = new ColumnText(writer.getDirectContent());
        column.setSimpleColumn(36, 730, 569, 36);
        column.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
        column.addElement(new Paragraph("Wrong: " + MOVIE_WITH_SPACES, font));
        column.addElement(new Paragraph(MOVIE, font));
        column.go();
        // step 5
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new Ligatures2().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class Ligatures2 : IWriter {
// ===========================================================================
    /** Correct movie title. */
    public const string MOVIE = 
    "\u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628";
    /** Correct movie title. */
    public const string MOVIE_WITH_SPACES = 
    "\u0644 \u0648 \u0631 \u0627 \u0646 \u0633   \u0627 \u0644 \u0639 \u0631 \u0628";
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        BaseFont bf = BaseFont.CreateFont(
          "c:/windows/fonts/arialuni.ttf", 
          BaseFont.IDENTITY_H, BaseFont.EMBEDDED
        );
        Font font = new Font(bf, 20);
        document.Add(new Paragraph("Movie title: Lawrence of Arabia (UK)"));
        document.Add(new Paragraph("directed by David Lean"));
        document.Add(new Paragraph("Wrong: " + MOVIE, font));
        ColumnText column = new ColumnText(writer.DirectContent);
        column.SetSimpleColumn(36, 730, 569, 36);
        column.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
        column.AddElement(new Paragraph("Wrong: " + MOVIE_WITH_SPACES, font));
        column.AddElement(new Paragraph(MOVIE, font));
        column.Go();
      }
    }
// ===========================================================================
  }
}


fontfactoryexample

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

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

public class FontFactoryExample {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/font_factory.pdf";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4:
        Font font = FontFactory.getFont("Times-Roman");
        document.add(new Paragraph("Times-Roman", font));
        Font fontbold = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
        document.add(new Paragraph("Times-Roman, Bold", fontbold));
        document.add(Chunk.NEWLINE);
        FontFactory.register("c:/windows/fonts/garabd.ttf", "my_bold_font");
        Font myBoldFont = FontFactory.getFont("my_bold_font");
        BaseFont bf = myBoldFont.getBaseFont();
        document.add(new Paragraph(bf.getPostscriptFontName(), myBoldFont));
        String[][] name = bf.getFullFontName();
        for (int i = 0; i < name.length; i++) {
            document.add(new Paragraph(name[i][3] + " (" + name[i][0]
                    + "; " + name[i][1] + "; " + name[i][2] + ")"));
        }
        Font myBoldFont2 = FontFactory.getFont("Garamond vet");
        document.add(new Paragraph("Garamond Vet", myBoldFont2));
        document.add(Chunk.NEWLINE);
        document.add(new Paragraph("Registered fonts:"));
        FontFactory.registerDirectory("resources/fonts");
        for (String f : FontFactory.getRegisteredFonts()) {
            document.add(new Paragraph(f, FontFactory.getFont(f, "", BaseFont.EMBEDDED)));
        }
        document.add(Chunk.NEWLINE);
        Font cmr10 = FontFactory.getFont("cmr10");
        cmr10.getBaseFont().setPostscriptFontName("Computer Modern Regular");
        Font computerModern = FontFactory.getFont("Computer Modern Regular", "", BaseFont.EMBEDDED);
        document.add(new Paragraph("Computer Modern", computerModern));
        document.add(Chunk.NEWLINE);
        FontFactory.registerDirectories();
        for (String f : FontFactory.getRegisteredFamilies()) {
            document.add(new Paragraph(f));
        }
        document.add(Chunk.NEWLINE);
        Font garamond = FontFactory.getFont("garamond", BaseFont.WINANSI, BaseFont.EMBEDDED);
        document.add(new Paragraph("Garamond", garamond));
        Font garamondItalic
            = FontFactory.getFont("Garamond", BaseFont.WINANSI, BaseFont.EMBEDDED, 12, Font.ITALIC);
        document.add(new Paragraph("Garamond-Italic", garamondItalic));
        // step 5
        document.close();
    }


    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new FontFactoryExample().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class FontFactoryExample : IWriter {
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        Font font = FontFactory.GetFont("Times-Roman");
        document.Add(new Paragraph("Times-Roman", font));
        Font fontbold = FontFactory.GetFont("Times-Roman", 12, Font.BOLD);
        document.Add(new Paragraph("Times-Roman, Bold", fontbold));
        document.Add(Chunk.NEWLINE);
        FontFactory.Register("c:/windows/fonts/garabd.ttf", "my_bold_font");
        Font myBoldFont = FontFactory.GetFont("my_bold_font");
        BaseFont bf = myBoldFont.BaseFont;
        document.Add(new Paragraph(bf.PostscriptFontName, myBoldFont));
        String[][] name = bf.FullFontName;
        for (int i = 0; i < name.Length; i++) {
          document.Add(new Paragraph(
            name[i][3] + " (" + name[i][0]
            + "; " + name[i][1] + "; " + name[i][2] + ")"
          ));
        }
        Font myBoldFont2 = FontFactory.GetFont("Garamond vet");
        document.Add(new Paragraph("Garamond Vet", myBoldFont2));
        document.Add(Chunk.NEWLINE);
        document.Add(new Paragraph("Registered fonts:"));
        FontFactory.RegisterDirectory(Utility.ResourceFonts); 
/*               
        string fontDirectory = Utility.ResourceFonts;
        FontFactory.RegisterDirectory(
          fontDirectory.Substring(0, fontDirectory.Length - 3
        ));
 */
        foreach (String f in FontFactory.RegisteredFonts) {
          document.Add(new Paragraph(
            f, FontFactory.GetFont(f, "", BaseFont.EMBEDDED
          )));
        }
        document.Add(Chunk.NEWLINE);
        Font cmr10 = FontFactory.GetFont("cmr10");
        cmr10.BaseFont.PostscriptFontName = "Computer Modern Regular";
        Font computerModern = FontFactory.GetFont(
          "Computer Modern Regular", "", BaseFont.EMBEDDED
        );
        document.Add(new Paragraph("Computer Modern", computerModern));
        document.Add(Chunk.NEWLINE);
        FontFactory.RegisterDirectories();
        foreach (String f in FontFactory.RegisteredFamilies) {
          document.Add(new Paragraph(f));
        }
        document.Add(Chunk.NEWLINE);
        Font garamond = FontFactory.GetFont(
          "garamond", BaseFont.WINANSI, BaseFont.EMBEDDED
        );
        document.Add(new Paragraph("Garamond", garamond));
        Font garamondItalic = FontFactory.GetFont(
          "Garamond", BaseFont.WINANSI, BaseFont.EMBEDDED, 12, Font.ITALIC
        );
        document.Add(new Paragraph("Garamond-Italic", garamondItalic));
      }
    }
// ===========================================================================
  }
}


fontselectionexample

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.FontSelector;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * This example was written by Bruno Lowagie. It is part of the book 'iText in
 * Action' by Manning Publications. 
 * ISBN: 1932394796
 * http://www.1t3xt.com/docs/book.php 
 * http://www.manning.com/lowagie/
 */

public class FontSelectionExample {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/font_selection.pdf";
    /** Some text */
    public static final String TEXT
        = "These are the protagonists in 'Hero', a movie by Zhang Yimou:\n"
            + "\u7121\u540d (Nameless), \u6b98\u528d (Broken Sword), "
            + "\u98db\u96ea (Flying Snow), \u5982\u6708 (Moon), "
            + "\u79e6\u738b (the King), and \u9577\u7a7a (Sky).";

    /**
     * Creates a PDF document.
     * @param filename the path to the new PDF document
     * @throws DocumentException 
     * @throws IOException 
     * @throws    DocumentException 
     * @throws    IOException
     */
    public void createPdf(String filename) throws IOException, DocumentException {
        // step 1
        Document document = new Document(PageSize.A4);
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3: we open the document
        document.open();
        // step 4:
        FontSelector selector = new FontSelector();
        Font f1 = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12);
        f1.setColor(BaseColor.BLUE);
        Font f2 = FontFactory.getFont("MSung-Light",
                "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED);
        f2.setColor(BaseColor.RED);
        selector.addFont(f1);
        selector.addFont(f2);
        Phrase ph = selector.process(TEXT);
        document.add(new Paragraph(ph));
        // step 5: we close the document
        document.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, DocumentException {
        new FontSelectionExample().createPdf(RESULT);
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class FontSelectionExample : IWriter {
// ===========================================================================
    /** Some text */
    public readonly string TEXT =
    "These are the protagonists in 'Hero', a movie by Zhang Yimou:\n"
    + "\u7121\u540d (Nameless), \u6b98\u528d (Broken Sword), "
    + "\u98db\u96ea (Flying Snow), \u5982\u6708 (Moon), "
    + "\u79e6\u738b (the King), and \u9577\u7a7a (Sky).";
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document(PageSize.A4)) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        FontSelector selector = new FontSelector();
        selector.AddFont(FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12));
        selector.AddFont(FontFactory.GetFont(
          "MSung-Light", "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED
        ));
        Phrase ph = selector.Process(TEXT);
        document.Add(new Paragraph(ph));
      }
    }
// ===========================================================================
  }
}


peace

JAVA

JAVA
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part3.chapter11;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.itextpdf.text.Document;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.FontSelector;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class Peace extends DefaultHandler {

    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part3/chapter11/peace.pdf";
    
    /** The XML file with the text. */
    public static final String RESOURCE
        = "resources/xml/peace.xml";
    
    /** Paths to and encodings of fonts we're going to use in this example */
    public static String[][] FONTS = {
        {"c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H},
        {"resources/fonts/abserif4_5.ttf", BaseFont.IDENTITY_H},
        {"resources/fonts/damase.ttf", BaseFont.IDENTITY_H},
        {"resources/fonts/fsex2p00_public.ttf", BaseFont.IDENTITY_H}
    };
    
    /** Holds he fonts that can be used for the peace message. */
    public FontSelector fs;

    /** The columns that contains the message. */
    protected PdfPTable table;

    /** The language. */
    protected String language;

    /** The countries. */
    protected String countries;

    /** Indicates when the text should be written from right to left. */
    protected boolean rtl;

    /** The StringBuffer that holds the characters. */
    protected StringBuffer buf = new StringBuffer();

    /**
     * Creates the handler for the pace.xml file.
     */
    public Peace() {
        fs = new FontSelector();
        for (int i = 0; i < FONTS.length; i++) {
            fs.addFont(FontFactory.getFont(FONTS[i][0], FONTS[i][1], BaseFont.EMBEDDED));
        }
        table = new PdfPTable(3);
        table.getDefaultCell().setPadding(3);
        table.getDefaultCell().setUseAscender(true);
        table.getDefaultCell().setUseDescender(true);
    }

    /**
     * @see org.xml.sax.ContentHandler#startElement(java.lang.String,
     *      java.lang.String, java.lang.String, org.xml.sax.Attributes)
     */
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        if ("pace".equals(qName)) {
            buf = new StringBuffer();
            language = attributes.getValue("language");
            countries = attributes.getValue("countries");
            if ("RTL".equals(attributes.getValue("direction"))) {
                rtl = true;
            } else {
                rtl = false;
            }
        }
    }

    /**
     * @see org.xml.sax.ContentHandler#endElement(java.lang.String,
     *      java.lang.String, java.lang.String)
     */
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if ("pace".equals(qName)) {
            PdfPCell cell = new PdfPCell();
            cell.addElement(fs.process(buf.toString()));
            cell.setPadding(3);
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            if (rtl) {
                cell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
            }
            table.addCell(language);
            table.addCell(cell);
            table.addCell(countries);
        }
    }

    /**
     * @see org.xml.sax.ContentHandler#characters(char[], int, int)
     */
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        buf.append(ch, start, length);
    }

    /**
     * Returns the table.
     * 
     * @return the PdfPTable (get it after using the parser)
     */
    public PdfPTable getTable() {
        return table;
    }

    /**
     * This example reads a text file written in UTF-8. Each line is a pipe
     * delimited array containing the name of a language, the word 'peace'
     * written in that language
     * 
     * @param args
     *            no arguments needed
     */
    public static void main(String[] args) {
        // step 1
        Document doc = new Document(PageSize.A4.rotate());
        try {
            // step 2
            PdfWriter.getInstance(doc, new FileOutputStream(RESULT));
            // step 3
            doc.open();
            // step 4
            Peace p = new Peace();
            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
            parser.parse(new InputSource(new FileInputStream(RESOURCE)), p);
            doc.add(p.getTable());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // step 5
        doc.close();
    }
}

C#

C#
/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */
using System;
using System.IO;
using Ionic.Zip;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace kuujinbo.iTextInAction2Ed.Chapter11 {
  public class Peace : IWriter {
// ===========================================================================
    /** The resulting PDF file. */
    public const String RESULT = "peace.pdf";
    /** The XML file with the text. */
    public static string RESOURCE = Path.Combine(
      Utility.ResourceXml, "peace.xml"
    );
    public readonly string FONT_PATH = Utility.ResourceFonts;
    /** Paths to and encodings of fonts we're going to use in this example */
    public string[][] FONTS { 
      get { return new string[][] {
          new string[] {
            "c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H
          },
          new string[] {
            string.Format(FONT_PATH, "abserif4_5.ttf"), BaseFont.IDENTITY_H
          },
          new string[] {
            string.Format(FONT_PATH, "damase.ttf"), BaseFont.IDENTITY_H
          },
          new string[] {
            string.Format(FONT_PATH, "fsex2p00_public.ttf"), BaseFont.IDENTITY_H
          }
        };
      }
    }
    /** Holds he fonts that can be used for the peace message. */
    public FontSelector fs;

    /** The columns that contains the message. */
    protected PdfPTable table;

    /** The language. */
    protected String language;

    /** The countries. */
    protected String countries;

    /** Indicates when the text should be written from right to left. */
    protected bool rtl; 
    
    /** The StringBuilder that holds the characters. */
    protected StringBuilder buf = new StringBuilder();
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        zip.AddFile(RESOURCE, "");       
        using (MemoryStream ms = new MemoryStream()) {
          using (Document document = new Document(PageSize.A4.Rotate())) {
            // step 2
            PdfWriter.GetInstance(document, ms);
            // step 3
            document.Open();
            // step 4
            fs = new FontSelector();
            for (int i = 0; i < FONTS.Length; i++) {
              fs.AddFont(FontFactory.GetFont(
                FONTS[i][0], FONTS[i][1], BaseFont.EMBEDDED
              ));
            }
            table = new PdfPTable(3);
            table.DefaultCell.Padding = 3;
            table.DefaultCell.UseAscender = true;
            table.DefaultCell.UseDescender = true;
            
            using (XmlReader xr = XmlReader.Create(RESOURCE)) {
              xr.MoveToContent();
              while (xr.Read()) {
                switch (xr.NodeType) {
                  case XmlNodeType.Element:
                    StartElement(xr);
                    break;
                  case XmlNodeType.Text:
                    buf.Append(xr.Value.Trim());
                    break;
                  case XmlNodeType.EndElement:
                    EndElement(xr.Name);
                    break;
                }
              }
            }        
            document.Add(table); 
          }
          zip.AddEntry(RESULT, ms.ToArray());
        }
        zip.Save(stream);             
      }
    }
// ---------------------------------------------------------------------------
    public void StartElement(XmlReader xr) {
      string name =  xr.Name;
      if ("pace".Equals(name)) {
        buf = new StringBuilder();
        language = xr.GetAttribute("language");
        countries = xr.GetAttribute("countries");
        rtl = "RTL".Equals(xr.GetAttribute("direction")) ? true : false;
      }
    }
// ---------------------------------------------------------------------------
    public void EndElement(string name) {
      if ("pace".Equals(name)) {
        PdfPCell cell = new PdfPCell();
        cell.AddElement(fs.Process(buf.ToString()));
        cell.Padding = 3;
        cell.UseAscender = true;
        cell.UseDescender = true;
        if (rtl) {
          cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
        }
        table.AddCell(language);
        table.AddCell(cell);
        table.AddCell(countries);
      }    
    }    
// ===========================================================================
  }
}
JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.