iText PDF を使い PDF ファイルを生成してみる
iText PDF とは,Java から PDF ファイルを生成する機能などを持ったソフトウェア
【関連する外部ページ】: http://park.geocities.jp/gdfsm000/
【関連する外部ページ】: http://www.atmarkit.co.jp/fjava/javatips/134java025.html
【関連する外部ページ】: https://codezine.jp/article/detail/462?p=2
【関連する外部ページ】: https://codezine.jp/article/detail/84
iTextPDF のインストール
- iTextPDF の Web ページを開く http://itextpdf.com/
- 「DOWNLOAD IT HERE」をクリック
- iText-5.0.6.jar のダウンロード
- iTextAsian.jar, iTextAisanCmaps.jar のダウンロード
- iText-5.0.6.jar, iTextAsian.jar, iTextAisanCmaps.jar を分かりやすいディレクトリに置く
- iText-5.0.6.jar, iTextAsian.jar, iTextAisanCmaps.jar のファイル名をフルパスで CLASSPATH に含める
◆ .bashrc の設定例
export CLASSPATH="${HOME}/iText-5.0.6.jar;${HOME}/iTextAsian.jar;${HOME}/iTextAsianCmaps.jar"
- tutorial.tar.gz をダウンロード
テスト実行
/*
* $Id: HelloWorld.java,v 1.6 2005/05/09 11:52:44 blowagie Exp $
* $Name: $
*
* This code is part of the 'iText Tutorial'.
* You can find the complete tutorial at the following address:
* http://itextdocs.lowagie.com/tutorial/
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* itext-questions@lists.sourceforge.net
*/
/* package com.lowagie.examples.general;*/
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
// see also http://www.atmarkit.co.jp/fjava/javatips/134java025.html
public class HelloWorld {
// 「① ② I Ⅱ ㍉ ㌢ ㈱」は Shift_JIS にはなく,Shift_JIS を拡張した文字コードセットである Windows-31J にある
// 「‖ 〜 − ¢ £ ¬」は Shift_JIS, EUC-JP, ISO-2022-JP では同じ文字コードなのに Windows-31J では違う文字コード
// # 「構」は Shift_JIS では 2 バイト目が「5C」になっている
final static private String TEXT="こんにちは \n コンニチハ\n ① ② I Ⅱ ㍉ ㌢ ㈱\n ‖ 〜 − ¢ £ ¬ \n 構わない \n 〒";
final static private String FILENAME="HelloWorld.pdf";
/**
* Generates a PDF file with the text 'Hello World'
*/
public static void main(String[] args) {
System.out.println(TEXT);
// step 1: creation of a document-object
Document doc = new Document();
try {
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.getInstance(doc, new FileOutputStream(FILENAME));
// step 3: we open the document
doc.open();
Font font = new Font(BaseFont.createFont("HeiseiKakuGo-W5",
"UniJIS-UCS2-H",
BaseFont.NOT_EMBEDDED));
// step 4: we add a paragraph to the document
doc.add(new Paragraph(text, font));
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
// step 5: we close the document
doc.close();
}
}
- 上記のサンプルプログラムを実行してみる.
javac HelloWorld.java java HelloWorld
- HelloWorld.pdf ができる.大成功
次のように「HeiseiKakuGo-W5 with UniJIS-0UCS2-H is not recognized」というエラーが出る場合には、 環境変数 CLASSPATH に iTextAsian.jar のファイル名をフルパスで追加すると解決することがある.