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

今回は、「iText」を使用して、表をPDFに配置する方法を紹介する。

ポイントは、表に対応するクラスである「PdfPTable」と、表内のセル(表の要素)に対応するクラスである「PdfPCell」の使用である。

手順としては、「PdfPCell」のコンストラクタで、表内に表示した文字をセル毎に作成し、「PdfPTable」の『addCell』メソッドで表に追加する。最後に「PdfPTable」をドキュメントに追加する。

<ソースコード>

package jp.co.smp.pdf.action;

import java.io.FileOutputStream;
import java.io.IOException;
import org.seasar.struts.annotation.Execute;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
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);
		
		//フォントの設定
		Font font = new Font(BaseFont.createFont("HeiseiKakuGo-W5",
				     "UniJIS-UCS2-H",BaseFont.NOT_EMBEDDED),11);
		
		//文章オブジェクト オープン
		doc.open();
		
		//表を作成(2列)
		PdfPTable pdfPTable = new PdfPTable(2);
		
		//表の要素(列タイトル)を作成
		PdfPCell cell1_1 = new PdfPCell(new Paragraph("商品名", font));
		cell1_1.setGrayFill(0.8f);		//セルを灰色に設定
		
		//表の要素(列タイトル)を作成
		PdfPCell cell1_2 = new PdfPCell(new Paragraph("価格", font));
		cell1_2.setGrayFill(0.8f);		//セルを灰色に設定
		
		//表の要素を作成
		PdfPCell cell2_1 = new PdfPCell(new Paragraph("赤福もち", font));
		
		//表の要素を作成
		PdfPCell cell2_2 = new PdfPCell(new Paragraph("1,200円", font));
		
		//表の要素を表に追加する
		pdfPTable.addCell(cell1_1);
		pdfPTable.addCell(cell1_2);
		pdfPTable.addCell(cell2_1);
		pdfPTable.addCell(cell2_2);
		
		//表を文章に追加する
		doc.add(pdfPTable);
	
		//文章オブジェクト クローズ
		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ライブラリ)【表配置編】

<お勧め書籍>