Create pdf with image using java


import java.io.FileNotFoundException;
import java.io.FileOutputStream;


import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;


public class GeneratePDFWithImageDemo {
  public static void main(String[] args) {
         new GeneratePDFWithImageDemo().createPDF();
  }


  public void createPDF(){
 Document document = new Document();
      try {
        PdfWriter.getInstance(document, 
        new FileOutputStream("C://Test.pdf"));
        document.open();
        PdfPTable table = new PdfPTable(1); //1 column.    
        Image image = Image.getInstance("C://Image/MyImage.jpg");
   image.scaleToFit(800f, 600f);
        image.scaleAbsolute(800f,600f);   // Give the size of image you want to print on pdf
PdfPCell nestedImgCell=new PdfPCell(image);
table.addCell(nestedImgCell);
        document.add(table);
        document.close ();
      }catch (FileNotFoundException e) {
           e.printStackTrace();
      } catch (DocumentException e) {
           e.printStackTrace();
      }catch (Exception e) {
           e.printStackTrace();
      }
      System.out.println("======== PDF Created Successfully =========);
   }
}

Popular posts from this blog

Can not connect to git using ssh (Permissions 0644 for '/root/.ssh/id_rsa' are too open.

Upload file on Google cloud storage using Java servlet on google app engine

Session timeout interceptor in struts 2