最近の更新

2012年4月30日月曜日

iText2.1.7でレイヤに画像を表示する方法

【目的】
iText2.1.7のライブラリを使用し、PDFでレイヤに画像を使用したPDFを作成する。



【手順】
1.「Javaプロジェクトの作成方法」の手順で、「iTextSample008-LayerImage」といプロジェクトを作成。
2.「itext-2.1.7.jarをライブラリに設定する方法」の手順で、プロジェクトに「itext-2.1.7.jar」のライブラリを追加。
3.「Javaクラスファイルの作成方法」の手順で、「Main」というクラスを作成。
4.「Main.java」を以下の様に入力。
import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfLayer;
import com.lowagie.text.pdf.PdfWriter;

public class Main {
    public static final String OUTPUT_FILE_NAME = "LayerImage.pdf";
    public static final String IMAGE = "HelloImage.jpg";

    public static void main(String[] args) throws DocumentException,
            IOException {
        Document document = new Document(PageSize.A3.rotate());
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(OUTPUT_FILE_NAME));
        writer.setViewerPreferences(PdfWriter.PageModeUseOC);

        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfLayer layer = new PdfLayer("Layer Sample", writer);

        Image img = Image.getInstance(IMAGE);
        img.setLayer(layer);
        img.setAbsolutePosition(50, 50);
        cb.addImage(img);

        document.close();
    }
}
5.「Ctrl+Shift+O」を押し、パッケージのインポート文を補完。
6.「Ctrl+Shift+F」を押し、ソースコードをフォーマッティング。
7.「HelloImage.jpg」をコピーし、「iTextSample008-LayerImage」上で「Ctrl+V」で貼り付け。
8.「Javaプロジェクトの実行方法」の手順で、「Main.java」を実行。
9.コンソールにエラーが出力されていないか確認。
(※コンソールが表示されていない場合は、「コンソール・ビューの表示方法」を確認)
10.「リフレッシュ(ローカルファイルとの同期)の方法」の手順で、プロジェクトをリフレッシュ。
11.「iTextSample008-LayerImage/LayerImage.pdf」が作成されています。
12.「iTextSample008-LayerImage/LayerImage.pdf」をダブルクリック。
13.「LayerImage.pdf」が以下の様に開き、「HelloImage.jpg」がPDFに埋め込まれて表示されれば成功です。




14.レイヤーのアイコンをクリックすればレイヤが非表示になります




































以上です。


0 件のコメント:

コメントを投稿

注: コメントを投稿できるのは、このブログのメンバーだけです。

関連記事