JavaでPDFを自動生成する方法【iText使用/日本語対応サンプル付き】

Javaで帳票やレポートをPDFとして出力したいとき、iTextライブラリは非常に便利です。特に日本語対応が必要な現場では、フォント指定やエンコーディングにも注意が必要になります。

この記事では、iTextを使って日本語入りPDFを自動生成する方法を、サンプルコード付きで解説します。


この記事でわかること

  • iTextの基本的な使い方(PDF生成)
  • 日本語フォントを扱うための設定方法
  • テキスト・表・画像の追加方法
  • 実用的なサンプルコード

使用ライブラリ:iText 5系(オープンソース)

iTextはバージョンによってライセンスが異なるため、iText 5(AGPLライセンス)を使うことを前提に解説します。商用利用の場合はライセンスの確認をお忘れなく。


1. iTextの導入方法(Maven)

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

2. 最小構成のPDF出力サンプル

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;

public class SimplePdfGenerator {
    public static void main(String[] args) throws Exception {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("sample.pdf"));
        document.open();
        document.add(new Paragraph("Hello, PDF!"));
        document.close();
    }
}

3. 【日本語対応】フォントを設定して出力

日本語はデフォルトのフォントでは表示されません。日本語フォント(例:MSゴシックやIPAフォント)を明示的に指定します。

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

public class JapanesePdfGenerator {
    public static void main(String[] args) throws Exception {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("japanese_sample.pdf"));
        document.open();

        // フォント設定(フォントパスは環境に応じて変更)
        BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/msgothic.ttc,0", "Identity-H", BaseFont.EMBEDDED);
        Font font = new Font(baseFont, 12);

        document.add(new Paragraph("こんにちは、世界!これは日本語です。", font));
        document.close();
    }
}

注意:LinuxやMacの場合はIPAフォントなどを使用。フォントのフルパスを指定する必要があります。


4. 表(Table)の追加方法

PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100);

PdfPCell cell1 = new PdfPCell(new Phrase("名前", font));
PdfPCell cell2 = new PdfPCell(new Phrase("年齢", font));
PdfPCell cell3 = new PdfPCell(new Phrase("山田太郎", font));
PdfPCell cell4 = new PdfPCell(new Phrase("28", font));

table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);

document.add(table);

5. 画像の追加方法

Image image = Image.getInstance("logo.png"); // 相対 or 絶対パス
image.scaleToFit(100, 100);
document.add(image);

よくあるエラーと対処法

エラー内容対処法
PDFに日本語が表示されないBaseFontで日本語フォント(Identity-H)を指定
ファイルが書き込めない書き込み権限/PDF出力先のパス確認
フォントファイルが見つからないOS別に適切なフォントパスを使用する

まとめ

項目内容
ライブラリiText 5(オープンソース)
日本語対応BaseFont.createFont()で日本語フォント指定
PDF要素テキスト、表、画像など自由に挿入可能
注意点商用利用時のライセンスに注意

補足:iTextの代替ライブラリ

ライブラリ名特徴
Apache PDFBox純Java製・PDF編集も可能
OpenPDFiText 4ベースのLGPLライブラリ
JasperReports帳票向けの強力なツール(テンプレート可)
タイトルとURLをコピーしました