Content of ITextTest.java
package com.t4b.java.itext.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class ITextTest {
public static final String DEST = "pdfs/hello.pdf";
public static void main(String[] args) throws DocumentException, IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new ITextTest().createPdf(DEST);
}
public void createPdf(String dest) throws DocumentException, IOException {
Document doc = new Document(PageSize.A4.rotate());
PdfWriter.getInstance(doc, new FileOutputStream(dest));
doc.open();
float[] columnWidths = { 2, 5, 5 };
PdfPTable table = new PdfPTable(columnWidths);
table.setWidthPercentage(50);
table.getDefaultCell().setUseAscender(true);
table.getDefaultCell().setUseDescender(true);
Font f = new Font(FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.GRAYWHITE);
PdfPCell cell = new PdfPCell(new Phrase("This is a header", f));
cell.setBackgroundColor(GrayColor.GRAYBLACK);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setColspan(3);
table.addCell(cell);
table.getDefaultCell().setBackgroundColor(new GrayColor(0.75f));
for (int i = 0; i < 2; i++) {
table.addCell("#");
table.addCell("Roll No");
table.addCell("Avg. Marks");
}
table.setHeaderRows(3);
table.setFooterRows(1);
table.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
for (int counter = 1; counter < 101; counter++) {
table.addCell(String.valueOf(counter));
table.addCell("" + counter);
table.addCell("" + new Random().nextInt(100));
}
doc.add(table);
doc.close();
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.