Thursday, 27 October 2016

itext: Create table with no border

PdfPCell class represents a cell in PdfPTable. By using setBorder method of PdfPCell class we can disable/enable the border.

public void setBorder(final int border)

Ex:
PdfPCell cell = new PdfPCell(new Phrase("number", tableHeaderFont));
cell.setBorder(Rectangle.NO_BORDER);

Following is the complete working application.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
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";
 private static Font tableHeaderFont = FontFactory.getFont(FontFactory.TIMES_ROMAN, 16, Font.BOLD, BaseColor.RED);

 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);
  PdfPCell cell = new PdfPCell(new Phrase("number", tableHeaderFont));
  cell.setBorder(Rectangle.NO_BORDER);
  table.addCell(cell);

  cell.setPhrase(new Phrase("square", tableHeaderFont));
  table.addCell(cell);

  for (int i = 1; i < 11; i++) {
   cell.setPhrase(new Phrase(Integer.toString(i)));
   table.addCell(cell);

   cell.setPhrase(new Phrase(Integer.toString(i * i)));
   table.addCell(cell);
  }
  document.add(table);

  document.close();
 }
}




Previous                                                 Next                                                 Home

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

Friday, 21 October 2016

Itext: Rotating image

Image class provides following methods to rotate image.
setRotationDegrees()
setRotation()

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.PdfWriter;

public class TestImage {
    public static void main(String args[]) throws DocumentException, MalformedURLException, IOException {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("my_images.pdf"));
        document.open();

        Image image1 = Image.getInstance("lion.jpeg");
        image1.setRotationDegrees(45);
        document.add(image1);
        
        document.close();
    }
}



Previous                                                 Next                                                 Home

Itext: Position image at specific position

Image class provides the method ‘setAbsolutePosition’ to set the image at given position.

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.PdfWriter;

public class TestImage {
  public static void main(String args[]) throws DocumentException, MalformedURLException, IOException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("my_images.pdf"));
    document.open();

    Image image1 = Image.getInstance("lion.jpeg");
    image1.scalePercent(50);
    image1.setAbsolutePosition(400, 650);
    document.add(image1);
    
    document.close();
  }
}



Previous                                                 Next                                                 Home

Itext: Image object

Image class is used to add images to PDF document. Let me try to add some image to PDF document.

Image image1 = Image.getInstance("lion.jpeg");
document.add(image1);

Above statements adds an image to PDF document.
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class TestImage {
  public static void main(String args[]) throws DocumentException, MalformedURLException, IOException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("my_images.pdf"));
    document.open();

    Image image1 = Image.getInstance("lion.jpeg");
    document.add(image1);

    document.add(new Paragraph("\n\n"));

    String imageUrl = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7FbvPS4KetmkmLCmmAttnMdAHFwW6QktGMrDOh2gBmGGlOU2q2IGFRtsTd7C61tVgV5_hypbzpuZm6ZqzujN6Zva0uPfH39LS25spURGXuttQi8mgYLndgdcpcewn1I42X4vsvnqWM5Ry/s1600/Flying+Car.jpg";
    Image image2 = Image.getInstance(new URL(imageUrl));
    image2.scalePercent(40);
    document.add(image2);

    document.close();
  }
}


Run above application, you can able to see following kind of pdf document.




Previous                                                 Next                                                 Home

itext: Chapter and Section

What is Section?
Section is part of the document, where you can add paragraphs, list of elements, tables etc., Section class provides following constructors to define Section instance.

protected Section()
protected Section(final Paragraph title, final int numberDepth)

As you see, the constructors are protected. So you can use Section class by using the subclasses of Section class.

What is Chapter?
Chapter extends the functionality of Section class.

public class Chapter extends Section {
         ....
}

Chapter class provide following constructors to work with it.

public Chapter(int chapterNumber)
public Chapter(Paragraph title, int chapterNumber)
public Chapter(String title, int chapterNumber)

The chapter number is shown by default. If you don't want to see the chapter number, you have to set the numberdepth to 0.

public void setNumberDepth(final int numberDepth)
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class TestChapter {
 public static void main(String args[]) throws FileNotFoundException, DocumentException {
  Paragraph title = new Paragraph("Introduction To Java");
  Chapter chapter1 = new Chapter(title, 1);

  chapter1.addSection("Features of Java");
  chapter1.addSection("Hello World to Java");
  chapter1.addSection("Primitive types");

  Document document = new Document();
  PdfWriter.getInstance(document, new FileOutputStream("tutorials.pdf"));
  document.open();
  document.add(chapter1);
  document.close();
 }
}

Run above application, you can able to see following kind of screen.


Previous                                                 Next                                                 Home

Monday, 17 October 2016

File Tail implementation in Java

FileTail.java
import java.io.File;
import java.io.RandomAccessFile;

/**
 * Worker class to print the tail of a file. Use {@link FileTailUtil.getTail()}
 * method to get the tail of a file.
 * 
 */
public class FileTail implements Runnable {

 /**
  * Full Path of the file to watch
  */
 private String fileName;

 /**
  * Monitors the update of the file for every intervalTime seconds.
  */
 private int intervalTime = 2000;

 /**
  * Set the flag to true, to stop the execution of thread.
  */
 private volatile boolean stopThread = false;

 /**
  * File To watch
  */
 private File fileToWatch;

 /**
  * Variable used to get the last know position of the file
  */
 private long lastKnownPosition = 0;

 public FileTail(String fileName) {
  this(fileName, 2000);
 }

 public FileTail(String fileName, int intervalTime) {
  this.fileName = fileName;
  this.intervalTime = intervalTime;
  this.fileToWatch = new File(fileName);
 }

 @Override
 public void run() {

  if (!fileToWatch.exists()) {
   throw new IllegalArgumentException(fileName + " not exists");
  }
  try {
   while (!stopThread) {
    Thread.sleep(intervalTime);
    long fileLength = fileToWatch.length();

    /**
     * This case occur, when file is taken backup and new file
     * created with the same name.
     */
    if (fileLength < lastKnownPosition) {
     lastKnownPosition = 0;
    }
    if (fileLength > lastKnownPosition) {
     RandomAccessFile randomAccessFile = new RandomAccessFile(fileToWatch, "r");
     randomAccessFile.seek(lastKnownPosition);
     String line = null;
     while ((line = randomAccessFile.readLine()) != null) {
      System.out.println(line);
     }
     lastKnownPosition = randomAccessFile.getFilePointer();
     randomAccessFile.close();
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
   stopRunning();
  }

 }

 public boolean isStopThread() {
  return stopThread;
 }

 public void setStopThread(boolean stopThread) {
  this.stopThread = stopThread;
 }

 public void stopRunning() {
  stopThread = false;
 }

}

FileTailUtil.java
import java.io.File;

public class FileTailUtil {

 public static FileTail getTail(String fileToWatch) {
  if (fileToWatch == null || fileToWatch.isEmpty()) {
   throw new IllegalArgumentException("fileName shouldn't be empty");
  }

  /* Check for existence of file */
  File file = new File(fileToWatch);
  if (!file.exists()) {
   throw new IllegalArgumentException(fileToWatch + "doesn't exists");
  }

  FileTail fileTail = new FileTail(fileToWatch);
  Thread watcherThread = new Thread(fileTail);
  watcherThread.start();
  return fileTail;
 }
}

Main.java
public class Main {
 public static void main(String args[]) {
  if (args.length != 1) {
   System.out.println("usage: java Main fileName");
   return;
  }

  String fileToWatch = args[0];

  FileTail fileTail = FileTailUtil.getTail(fileToWatch);
 }
}