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

今回は、「iText」を使用して、図形(楕円と直線)をPDFに配置する方法を紹介する。

ポイントは、前回の四角形描画と同じく、「PdfGraphics2D」クラスを利用することである。

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

No. メソッド 概要
1 drawOval 楕円を描画する
2 fillOval 中を塗りつぶした楕円を描画する
3 drawArc 楕円をベースとする円弧を描画する

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

No. メソッド 概要
1 drawLine 直線を描画する

<ソースコード>

package jp.co.smp.pdf.action;

import java.awt.Color;
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.drawOval(10, 10, 100, 50);
		
		//色を指定して中を塗りつぶした楕円を描画
		pdfGraphics2D.setColor(new Color(255, 0, 255));
		pdfGraphics2D.fillOval(120, 10, 100, 50);
		
		//色を指定して円弧を描画する(※)
		pdfGraphics2D.setColor(new Color(0, 255, 0));
		pdfGraphics2D.drawArc(230, 10, 100, 50, 0, 180);
		
		//色を指定して直線を描画
		pdfGraphics2D.setColor(new Color(255, 0, 0));
		pdfGraphics2D.drawLine(10, 70, 110, 120);
		
		
		//PdfGraphics2Dの後処理
		pdfGraphics2D.dispose();
	
		//文章オブジェクト クローズ
		doc.close();
		
		//PDFWriter クローズ
		pdfwriter.close();
		
		return null;
	}
}

※円弧の第5引数・第6引数には、描画する円弧の開始角度と終了角度を指定する。

<実行結果>
実行すると、フォルダ「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ライブラリ)【表配置編】

<お勧め書籍>