Saturday 5 November 2016

itext: Align text in table

PdfPCell class provides to align the text in table cell.

public void setHorizontalAlignment(int horizontalAlignment)
public void setVerticalAlignment(int verticalAlignment)

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.Element;
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);

  PdfPCell cell = new PdfPCell();
  cell.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);

  cell.setPhrase(new Phrase("Core Java"));
  table.addCell(cell);

  cell.setPhrase(new Phrase(
    "An introduction to Java Technology, It is best place to start for a beginner. You can learn OOPs, threads, Collections etc.,"));
  table.addCell(cell);

  cell.setPhrase(new Phrase("Design Patterns"));
  table.addCell(cell);

  cell.setPhrase(new Phrase(
    "A software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. I documented mostly used design patterns here."));
  table.addCell(cell);

  document.add(table);

  document.close();
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment