PDFに表を描く [PdfWriter ]・Javaの小技、サンプル、ニュースなどを紹介していきます。みんなで参考にしてください。

Ads by Google


上記の広告は1ヶ月以上更新のないブログに表示されています。
新しい記事を書く事で広告が消せます。

PDFに表を描く [PdfWriter ]


PDFに表を描画するサンプルです。
PDF用のライブラリはiText.jarが以下のHPから
http://www.lowagie.com/iText/docs.html#download
日本語フォントを使用するために、iTextAsian.jarを以下からダウンロードしてください。
http://prdownloads.sourceforge.net/itext/iTextAsian.jar?download


Document doc = null;
PdfWriter writer = null;
PdfContentByte cb = null;
FileOutputStream fos = null;

//A4サイズのPDFを出力
doc = new Document(PageSize.A4,30,30,30,30);
fos = new FileOutputStream("出力ファイル名", false);
writer = PdfWriter.getInstance(doc, fos);

//PDFを開く
doc.open();

BaseFont jbfont = BaseFont.createFont("HeiseiMin-W3",
"UniJIS-UCS2-H", BaseFont.NOT_EMBEDDED);
//フォント指定
com.lowagie.text.Font jfont = new com.lowagie.text.Font(jbfont,7);

//例えばイメージの貼り付け
Image img00 = Image.getInstance(ファイル名);
img00.setAbsolutePosition(X座標, Y座標);
doc.add(img00);

Table table = new Table(1, 1);
table.setDefaultHorizontalAlignment(Element.ALIGN_RIGHT);
table.setWidth(100);
table.setPadding(1);
table.setSpacing(0);

//項目の幅
int[] hw = {5, 20, 32};

Table aTable = new Table(12,fc.size()+1);
aTable.setWidths(hw);
aTable.setWidth(98);

//項目作成
String[] cols = {"No", "氏名", "住所"};
for (int i = 0; i < cols.length; i++) {
Paragraph p = new Paragraph(cols[i], jfont);
Cell cell = new Cell(p);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
aTable.addCell(cell, new Point(0, i));
}

//データを表示
for (int i = 0; i < データ数; i++) {
Paragraph p = new Paragraph(""+(i+1), jfont);
Cell cell = new Cell(p);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
aTable.addCell(cell, new Point(i+1, 0));

p = new Paragraph(氏名, jfont);
cell = new Cell(p);
aTable.addCell(cell, new Point(i+1, 1));

p = new Paragraph(住所, jfont);
cell = new Cell(p);
aTable.addCell(cell, new Point(i+1, 2));
}

Paragraph para = new Paragraph("合計 ? 件", jfont);
para.setAlignment(Element.ALIGN_RIGHT);
Cell cell1 = new Cell(para);
cell1.add(aTable);//
table.addCell(cell1, new Point(0, 0));

doc.add(table);

//PDF作成 終了
doc.close();
fos.close();