Tuesday 1 November 2016

Itext: Adding background image to a cell in table

PdfPCell class provides setImage method to set an image in table cell.

public void setImage(Image image)

Following application adds images to table cells.
import java.io.File;
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.Image;
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 {

  /* 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();

  Image image = Image.getInstance("lion.jpeg");
  cell.setImage(image);
  table.addCell(cell);

  image = Image.getInstance("tiger.jpg");
  cell.setImage(image);
  table.addCell(cell);

  image = Image.getInstance("rabbit.jpeg");
  cell.setImage(image);
  table.addCell(cell);

  image = Image.getInstance("lion.jpeg");
  cell.setImage(image);
  table.addCell(cell);

  document.add(table);

  document.close();
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment