Thursday, 22 September 2016

Itext: Chunk: Add background color to chunk

In this post, I am going to explain how to add background color to Chunk object.

Chunk class provides setBackground method to set the background color to this chunk.

public Chunk setBackground(final BaseColor color)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class TestChunk {
 private static final String fileName = "/Users/harikrishna_gurram/Documents/itext/chunkEx.pdf";
 private static Font font = FontFactory.getFont(FontFactory.COURIER, 10, Font.ITALIC, BaseColor.BLACK);

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

  Chunk chunk = new Chunk("Hello World Itext", font);
  chunk.setBackground(BaseColor.GREEN);
  Paragraph p = new Paragraph(chunk);
  document.add(p);

  document.close();
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment