Monday 7 November 2016

Itext: Writing big tables

Sometimes you may want to write huge amount of data to tables, it definitely consumes lot of memory. To reduce this overhead, you can add data to table in chunks like 10 records at a time. By using setComplete method of PdfPTable you can achieve this.

Set the setComplete status to false.

Write k records to table and add the table to document.

Set the setComplete status to true.

Following is the complete working application.

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

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";

 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);
  table.setComplete(false);
  table.setHeaderRows(1);
  PdfPCell cell = new PdfPCell();

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

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

  for (int i = 1; i < 1000; i++) {
   if (i % 10 == 0) {
    document.add(table);
   }
   cell.setPhrase(new Phrase(Integer.toString(i)));
   table.addCell(cell);

   cell.setPhrase(new Phrase(Integer.toString(i * i)));
   table.addCell(cell);
  }
  table.setComplete(true);

  document.close();
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment