Thursday, 27 October 2016

itext: Create table with no border

PdfPCell class represents a cell in PdfPTable. By using setBorder method of PdfPCell class we can disable/enable the border.

public void setBorder(final int border)

Ex:
PdfPCell cell = new PdfPCell(new Phrase("number", tableHeaderFont));
cell.setBorder(Rectangle.NO_BORDER);

Following is the complete working application.
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.Rectangle;
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.RED);

 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.setBorder(Rectangle.NO_BORDER);
  table.addCell(cell);

  cell.setPhrase(new Phrase("square", tableHeaderFont));
  table.addCell(cell);

  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();
 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment