Table cells of iText PDF can be easily manipulated using the PdfPCell class. In this post we will see the how to use PdfPCell in tables of iText PDF.
com.itextpdf.text.pdf.PdfPCell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
package com.kscodes.examples.itext; import java.io.FileOutputStream; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPHeaderCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; public class TableExample2 { public static void main(String args[]) { String PDF_OUTPUT_FILE = "K:\\Kscodes\\pdf\\itext-cell-tables.pdf"; TableExample2 tableExample = new TableExample2(); tableExample.createPDF(PDF_OUTPUT_FILE); } private void createPDF(String fileName) { // Create a Document object Document document = new Document(); try { // Create a PdfWriter instance and use the document to write the pdf // to a specified location PdfWriter.getInstance(document, new FileOutputStream(fileName)); // open the document document.open(); // Create a Simple table PdfPTable table = new PdfPTable(3); // Add header details table.addCell(getHeaderCell("Fruit")); table.addCell(getHeaderCell("Quantity")); table.addCell(getHeaderCell("Price")); // Add Colorful data for first row table.addCell(getFirstRowFormatted("Apple")); table.addCell(getFirstRowFormatted("1")); table.addCell(getFirstRowFormatted("20")); // Add Rotated data for Second row table.addCell(getSecondRowFormatted("Orange")); table.addCell(getSecondRowFormatted("4")); table.addCell(getSecondRowFormatted("25")); document.add(table); // close the document document.close(); System.out.println("PDF created at the location !!!"); } catch (Exception e) { System.out.println("Exception occured :: " + e); } } private PdfPCell getHeaderCell(String text) { PdfPCell headerCell = new PdfPHeaderCell(); headerCell.setBackgroundColor(BaseColor.LIGHT_GRAY); headerCell.addElement(new Paragraph(text)); return headerCell; } private PdfPCell getFirstRowFormatted(String text) { PdfPCell pdfpCell = new PdfPCell(); pdfpCell.addElement(new Paragraph(text)); pdfpCell.setBackgroundColor(BaseColor.ORANGE); return pdfpCell; } private PdfPCell getSecondRowFormatted(String text) { PdfPCell pdfpCell = new PdfPCell(); pdfpCell.addElement(new Paragraph(text)); pdfpCell.setRotation(90); return pdfpCell; } } |
Output