LoginSignup
5
4

More than 5 years have passed since last update.

itext7でPDFを作成する~日本語を出力しよう~

Last updated at Posted at 2018-12-30

itext7で日本語を出そう

さて前回、HelloWorldを出力したものの、日本語の出力にしたら真っ白けなPDFが出力されてしまいました。
原因は「フォント」にあります。
日本語に対応したフォントを割り当ててあげないと日本語は出力されません!
というわけで、日本語出力例

HelloWorldJp.java
import java.io.File;

import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

public class HelloWorldJp {
    public static void main(String[] args) throws Exception {
        //Initialize PDF writer
        PdfWriter writer = new PdfWriter(new File("HelloWorldJp.pdf"));
        // 平成角ゴシック
        PdfFont font = PdfFontFactory.createFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H");

        //Initialize PDF document
        PdfDocument pdf = new PdfDocument(writer);

        // Initialize document
        Document document = new Document(pdf);

        //Add paragraph to the document
        document.add(new Paragraph("こんにちは~世界!").setFont(font));

        //Close document
        document.close();
   }
}

ポイントは「平成角ゴシック」のフォントを作って、文字にsetFontしている部分ですね。

他にはどんなフォントが使える?

gradleで読み込んだ「font-asian」で指定できる日本語を調べてみました。
第1引数は「フォント名」、第2引数は「エンコード」を指定できます。

  • 第1引数:フォント名
    • "HeiseiMin-W3":平成明朝
    • "HeiseiKakuGo-W5":平成角ゴシック
    • "KozMinPro-Regular":小塚明朝

※「font-asian-7.1.4.jar」の「com.itextpdf.io.font.cmap.cjk_registry.properties」というファイルで「fonts」に定義されているものが指定可能なフォント名のようです。
さらにこの名称のpropertiesファイルの中で「Registry=Adobe_Japan1」と定義されているものを日本語で指定できるフォントと判断しました。

  • 第2引数:エンコード 第1引数で指定したフォント名のエンコード方法を指定します。 「font-asian」を利用する場合は基本的には"UniJIS-UCS2-H"か"UniJIS-UTF16-H"を指定するのが良さそうです。 まずは後ろについている"-H"と"-V"ですが、"-V"は縦書きフォント用です。 縦書きについてはそのうちやる予定です。

※日本語で第2引数に他に指定できるものとしては「cjk_registry.properties」の「Adobe_Japan1」で定義されているものと思われます。
この中から半角数字や半角カナなどキチンと表示できそうなのがこの2つでした。
「彅」(草なぎのなぎ)や「♡」(ハートマーク)もこの2つでは表示できました。
「🍣」(寿司の絵文字)ではエラーとなってしまいました・・・

font-asian以外のフォントは使える?
とりあえず使えます。
例えばwindowsであればMSゴシックを指定できたりします。

PdfFont font = PdfFontFactory.createFont("c:\\windows\\fonts\\msgothic.ttc,0", "Identity-H");

ただ、フォントには著作権などあるので取扱には注意!!

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4