Wednesday 26 October 2016

Itext: Working with tables

PdfPTable is used to define tables in PDF document. PdfPTable class provides following constructors to define an instance.

public PdfPTable(final float relativeWidths[])
public PdfPTable(final int numColumns)
public PdfPTable(final PdfPTable table)

Following application creates a table of 2 columns, where column1 represents a number and column 2 represent square of the number.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
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";

 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);
  table.addCell("number");
  table.addCell("Square");
  for (int i = 1; i < 11; i++) {
   table.addCell(i + "");
   table.addCell(i * i + "");
  }
  document.add(table);

  document.close();
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment