kuujinbo_dot_info

What's CJK?

Posted 2008-07.

Use Chinese, Japanese, or Korean (CJK) fonts. This is short and sweet:

using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

public class cjk {
  public static void Main() {
    Document document = new Document();
    try {
      BaseFont.AddToResourceSearch("iTextAsian.dll");
      PdfWriter.GetInstance(
        document,
        new FileStream("cjk.pdf", FileMode.Create)
      );
      document.Open();
 
      string japanese = @"
Nice reading:

** ドラゴンボール
** ナルト
";
      BaseFont bf_japan = BaseFont.CreateFont(
        "HeiseiKakuGo-W5",
// 'H' => horizontal, replace last character with 'V' for vertical
        "UniJIS-UCS2-H",
        BaseFont.NOT_EMBEDDED
      );
      Font font_jpn = new Font(bf_japan, 8);
      Paragraph paragraph = new Paragraph(japanese, font_jpn);
      document.Add(paragraph);
      bf_japan = BaseFont.CreateFont(
        "KozMinPro-Regular",
        "UniJIS-UCS2-H",
        BaseFont.EMBEDDED
      );
      font_jpn = new Font(bf_japan, 8);
      paragraph = new Paragraph(japanese, font_jpn);
      document.Add(paragraph);
    }
    catch { throw; }
    finally { 
      if (document != null && document.IsOpen()) document.Close();
    }
  }
}

Notes

  • It's assumed that you already have basic knowledge of how to use iText[Sharp] and that you're reading this to use Chinese, Japanese, or Korean language(s) in your PDF, which also presumes you know something about Unicode.
  • Working with a CJK font is no different from working with any other font, call BaseFont.CreateFont() to get a BaseFont to start with. It took me a while to figure out all the available combinations for the first two parameters, the string/encoding names. At a minimum you need to download iTextAsian-1.0-dll.zip from the iTextSharp download page anyway, so get iTextAsian-1.0.zip too - the supported font (string) names with their respective encodings is listed in the file cjkfonts.properties. More good details about the process can be found here (albeit in Java, but with excellent general information about using fonts in iText).
  • If you take a look at an iText (Java) example using CJK you'll notice you don't need to do anything special (in your code) to use the fonts, but you do need iTextAsian.jar in your CLASSPATH. With iTextSharp you need to call BaseFont.AddToResourceSearch() to load the iTextAsian.dll assembly. That part was also a bit hard to find, but it is documented here.
  • Should be obvious in the lone comment, but to switch between horizontal and vertical writing, swap "H" and "V" on the last character on the second parameter of BaseFont.CreateFont().
  • Result PDF is here