JavaでPDFファイルを出力する(iTextライブラリ)【図形配置編】

今回は、「iText」を使用して、図形(四角形)をPDFに配置する方法を紹介する。

ポイントは、「PdfGraphics2D」クラスを使用して、四角形を描画するメソッドを呼び出し、最後に「dispose」メソッドを呼び出すことである。

「PdfGraphics2D」クラスの、四角形を描画するメソッドには、下記の様なものが用意されている。

No. メソッド 概要
1 drawRect 四角形を描画する
2 drawRoundRec 角が丸い四角形を描画する
3 fillRect 中を塗りつぶした四角形を描画する
4 fillRoundRect 中を塗りつぶした角が丸い四角形を描画する

また、使用する色に関しては、「PdfGraphics2D」クラスの「setColor」メソッドで指定する。

さらに、グラデーション使用したい場合は、「GradientPaint」クラスでグラデーションの情報を定義し、それを「PdfGraphics2D」クラスの「setPaint」メソッドで指定する。

<ソースコード>

package jp.co.smp.pdf.action;

import java.awt.Color;
import java.awt.GradientPaint;
import java.io.FileOutputStream;
import java.io.IOException;
import org.seasar.struts.annotation.Execute;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class IndexAction {
	
	@Execute(validator = false)
	public String index() {
		return "index.jsp";
	}
	
	@Execute(validator = false)
	public String createPdf() throws DocumentException, IOException{
		
		//文書オブジェクトを生成
		Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
		
		//出力先(アウトプットストリーム)の生成
		FileOutputStream fos = new FileOutputStream("C:\\temp\\test.pdf");
		
		//アウトプットストリームをPDFWriterに設定
		PdfWriter pdfwriter = PdfWriter.getInstance(doc, fos);
		
		//文章オブジェクト オープン
		doc.open();
		
		//PdfContentByteの取得
		PdfContentByte pdfContentByte = pdfwriter.getDirectContent();

		//PdfGraphics2D のインスタンス化
		PdfGraphics2D pdfGraphics2D = new PdfGraphics2D(pdfContentByte,
				                                doc.getPageSize().getWidth(),
				                                doc.getPageSize().getHeight());
		
		//四角を描画
		pdfGraphics2D.drawRect(10, 10, 100, 100);
		
		//色を指定して中を塗りつぶした四角を描画
		pdfGraphics2D.setColor(new Color(255, 0, 0));
		pdfGraphics2D.fillRect(120, 10, 100, 100);
		
		//色を指定して角が丸い四角を描画
		pdfGraphics2D.setColor(new Color(0, 0, 255));
		pdfGraphics2D.drawRoundRect(230, 10, 100, 100, 30, 30);
		
		//色を指定して角が丸く塗りつぶした四角を描画
		pdfGraphics2D.setColor(new Color(0, 255, 0));
		pdfGraphics2D.fillRoundRect(340, 10, 100, 100, 50, 50);
		
		//グラデーションで塗りつぶした四角を描画
		GradientPaint gradientPaint = new GradientPaint(10, 120, Color.ORANGE, 
                                                                110, 220, Color.GREEN);
		pdfGraphics2D.setPaint(gradientPaint);
		pdfGraphics2D.fillRect(10, 120, 100, 100);
		
		//PdfGraphics2Dの後処理
		pdfGraphics2D.dispose();
	
		//文章オブジェクト クローズ
		doc.close();
		
		//PDFWriter クローズ
		pdfwriter.close();
		
		return null;
	}
}

<実行結果>
実行すると、フォルダ「C:\temp」に「test.pdf」が作成される。

<関連記事>
JavaでPDFファイルを出力する(iTextライブラリ)【準備編】
JavaでPDFファイルを出力する(iTextライブラリ)【出力編】
JavaでPDFファイルを出力する(iTextライブラリ)【テキスト自由配置編】
JavaでPDFファイルを出力する(iTextライブラリ)【画像配置編】
JavaでPDFファイルを出力する(iTextライブラリ)【図形配置編】
JavaでPDFファイルを出力する(iTextライブラリ)【図形配置編2】
JavaでPDFファイルを出力する(iTextライブラリ)【表配置編】

<お勧め書籍>