PdfPCell class provides setBackgroundColor method, by using this you can change the Background Color of a table.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class TestTable {
private static final String fileName = "/Users/harikrishna_gurram/Documents/itext/tableEx.pdf";
private static Font tableHeaderFont = FontFactory.getFont(FontFactory.TIMES_ROMAN, 16, Font.BOLD, BaseColor.WHITE);
public static void main(String args[]) throws FileNotFoundException, DocumentException {
/* Create parent directories to destination pdf file */
File file = new File(fileName);
file.getParentFile().mkdirs();
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(fileName));
document.open();
PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell(new Phrase("number", tableHeaderFont));
cell.setBackgroundColor(BaseColor.BLACK);
table.addCell(cell);
cell.setPhrase(new Phrase("square", tableHeaderFont));
table.addCell(cell);
cell.setBackgroundColor(BaseColor.GRAY);
for (int i = 1; i 11; i++) {
cell.setPhrase(new Phrase(Integer.toString(i)));
table.addCell(cell);
cell.setPhrase(new Phrase(Integer.toString(i * i)));
table.addCell(cell);
}
document.add(table);
document.close();
}
}
This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here