Saturday 5 November 2016

itext: tables: Working with colspan and rowspan

PdfPCell class provides following methods to change the row span and column span.

public void setColspan(int colspan)
public void setRowspan(int rowspan)

Following is the complete working application.
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.List;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
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 List<String> months = Arrays.asList("January", "February", "March", "April", "May", "June", "July",
   "August", "September", "October", "November", "December");

 private static List<Integer> revenue = Arrays.asList(1000, 1234, 432, 5555, 1234, 9876, 765, 435, 765, 900, 324,
   543);

 public static void main(String args[]) throws DocumentException, MalformedURLException, IOException {

  Document document = new Document();
  PdfWriter.getInstance(document, new FileOutputStream(fileName));
  document.open();

  PdfPTable table = new PdfPTable(2);

  PdfPCell cell = new PdfPCell();

  cell.setPhrase(new Phrase("Month"));
  table.addCell(cell);

  cell.setPhrase(new Phrase("Revenue"));
  table.addCell(cell);

  int i = 0, sum = 0, amount = 0;
  for (String month : months) {
   cell.setPhrase(new Phrase(month));
   table.addCell(cell);

   amount = revenue.get(i);
   sum += amount;
   cell.setPhrase(new Phrase(Integer.toString(amount)));
   table.addCell(cell);
   i++;
  }

  cell.setColspan(2);
  cell.setBackgroundColor(BaseColor.RED);
  cell.setPhrase(new Phrase("Total Amount                                         " + sum));
  table.addCell(cell);

  document.add(table);

  document.close();
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment