Sunday, November 4, 2012

Exporting to PDF : iText

Posted by Sayan Guharoy

Exporting to PDF : iText

Itext API helps you to read/write a pdf file through your java code.In the below example we will create a blank pdf in the server.Read it,write out our content,push it from the server using a content-disposition and create a file download window prompt in the client side.

Firstly adobe pdf editor in not free and doesn't comes with the pdf viewer that we commonly use,which means we cant create a pdf file like a new word document.

We will do a simple trick here,we will create a word file ,use any of the online word to pdf converter utility and get a blank pdf :).I found most of the online pdf converter uses secured email option for dispatching which may get delayed due to bandwidth problems.
Better use this site http://www.doc-pdf.net/ which provides download instantaneously.

Once you created your empty pdf put it under C:\Report_ Export

Download itextpdf and add itextpdf.jar to your class path.

Now we will open the pdf and write out the content using itextpdf writer.
//import the following classes

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.html.WebColors;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

//create your font styling as you like
private static Font bigFont 
= new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD);
private static Font smallBold
 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD,BaseColor.BLACK);
private static Font tabletdcolor 
= new Font(Font.FontFamily.HELVETICA , 6, Font.NORMAL,BaseColor.BLACK);
private static Font tabletdcolorsmall 
= new Font(Font.FontFamily.HELVETICA , 5, Font.NORMAL,BaseColor.BLACK);
	

public  void createPdf(List<resultlist> resultlistDemo) {
	
//this method is getting called from main request servlet which extends http servlet I am passing servletContext here from my main servlet  	 
 	
   logger.debug("into pdf"+AppContext.getInstance().getServletContextpath());
   String servletContext=AppContext.getInstance().getServletContextpath();

//report drive will give me the drive letter where I have my empty pdf  

 	String reportdrive=servletContext.substring(0, 2);
 	String newfilename="hello.pdf";
 	String desdirectry2=reportdrive+"\\Report_ Export";
  	String destFileName2 = desdirectry2+"\\"+newfilename;
  	int index = 0;
  	    
  //you can use your own color codes by creating new BaseColor objects as 
  //shown below
       
             String tabletrcolor="#D5D4D5";
  	     String tableheadercolor="E5E1E7";

   	    BaseColor bordercolor = WebColors.getRGBColor(tabletrcolor);
   	    BaseColor btableheadercolor = WebColors.getRGBColor(tableheadercolor);
  	    
 	   try{ 
 
     //set the dimension of your pdf

      Document document=new Document(PageSize.A4_LANDSCAPE,10,10,10,10);

     //load the blank pdf

       PdfWriter.getInstance(document,new FileOutputStream(destFileName2));
       document.open();

    //Your Title 

       document.add(new Paragraph("TRAIN TIMINGS", bigFont));

    //you can use info generated report options like time,user created

    document.add(new Paragraph("Report generated by: " 
           + System.getProperty("user.name") 
           + ", " + new Date(), smallBold));
    
//use this to create a blank line

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

    //change the column widths

       float[] columnWidths = {22f, 74f, 16f,16f, 12f};

    //define the number columns in the table

       PdfPTable table = new PdfPTable(5);
       table.setWidthPercentage(100);
       table.setWidths(columnWidths);
        
       
       PdfPCell c1 = new PdfPCell(new Paragraph("TRAIN", smallBold));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       c1.setBackgroundColor(btableheadercolor);
       c1.setPaddingRight(5);
       c1.setPaddingBottom(5);
       c1.setBorderColor(bordercolor);
       table.addCell(c1);

       c1 = new PdfPCell(new Paragraph("DESCRIPTION", smallBold));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       c1.setBackgroundColor(btableheadercolor);
       c1.setPaddingRight(5);
       c1.setPaddingBottom(5);
       c1.setBorderColor(bordercolor);
       table.addCell(c1);

       c1 = new PdfPCell(new Paragraph("FROM LOC", smallBold));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       c1.setBackgroundColor(btableheadercolor);
       c1.setPaddingRight(5);
       c1.setPaddingBottom(5);
       c1.setBorderColor(bordercolor);
       table.addCell(c1);
        
       c1 = new PdfPCell(new Paragraph("TO LOC", smallBold));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       c1.setBackgroundColor(btableheadercolor);
       c1.setPaddingRight(5);
       c1.setPaddingBottom(5);
       c1.setBorderColor(bordercolor);
       table.addCell(c1);
        
       c1 = new PdfPCell(new Paragraph("STATUS", smallBold));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       c1.setBackgroundColor(btableheadercolor);
       c1.setPaddingRight(5);
       c1.setPaddingBottom(5);
       c1.setBorderColor(bordercolor);
       table.addCell(c1);
       table.setHeaderRows(1);
       
         
   for(resultlist s: resultlistDemo){  
 	   
   //you can set a alternate row color 

     if(index%2==0)tabletrcolor="#F7F4F7" ; else tabletrcolor="#FFF";

     BaseColor myColor = WebColors.getRGBColor(tabletrcolor);
 	   
       c1 = new PdfPCell(new Paragraph(s.getTrainName(), tabletdcolor));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       c1.setBackgroundColor(myColor);
       c1.setPaddingRight(5);
       c1.setPaddingBottom(5);
       c1.setBorderColor(bordercolor);
       table.addCell(c1);
 	   
 	c1 = new PdfPCell(new Paragraph("Train details for "+s.getTrainNo()+" "+ "to location"+	 s.getCurrentloc() +" from Location " + s.getPreviousloc()+" Event "+ s.getEvent(), tabletdcolor));
       
       c1.setHorizontalAlignment(Element.ALIGN_LEFT);
       c1.setBackgroundColor(myColor);
       c1.setPaddingRight(5);
       c1.setPaddingBottom(5);
       c1.setBorderColor(bordercolor);
       table.addCell(c1);
       
       c1 = new PdfPCell(new Paragraph(s.getArrivalDate(), tabletdcolor));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       c1.setBackgroundColor(myColor);
       c1.setPaddingRight(5);
       c1.setPaddingBottom(5);
       c1.setBorderColor(bordercolor);
       table.addCell(c1);
       
       c1 = new PdfPCell(new Paragraph(s.getDepartureDate(), tabletdcolor));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       c1.setBackgroundColor(myColor);
       c1.setPaddingRight(5);
       c1.setPaddingBottom(5);
       c1.setBorderColor(bordercolor);
       table.addCell(c1);
       
       c1 = new PdfPCell(new Paragraph(s.getStatus(), tabletdcolor));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       c1.setBackgroundColor(myColor);
       c1.setPaddingRight(5);
       c1.setPaddingBottom(5);
       c1.setBorderColor(bordercolor);
       table.addCell(c1);
       
       index++;
      
   }
       document.add(table);
       document.close(); 
 	   }
 	   catch (Exception e)
 	   {
  	  logger.debug("eror in export pdf"+e.getMessage());
 	   }
}
5. Additionally if we want a hyperlink that will allow access of this report from client side browser we will create a url pattern in the servlet and a java class that will open the exported file copy the content and stream the content in the response, also we will set the response header mime type to pdf so that browser recognizes it and give user a option to save or open the excel. Let write the java file first
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//our servlet will extend HttpServlet  

public class MyServlet extends HttpServlet{
 
  private static final int BYTES_DOWNLOAD = 1024;
 
  public void doGet(HttpServletRequest request, 
   HttpServletResponse response) throws IOException{
 
//set the content type as pdf

response.setContentType("application/pdf");
response.setHeader("Content-Disposition",
                     "attachment;filename=hello.pdf");

//we will get report drive same way we are doing while creating the report

ServletContext ctx = getServletContext();
String    reportdrive=getServletContext().getRealPath("/").toString().substring(0, 2);
 
String desdirectry=reportdrive+"\\result_reports";
String newfilename="hello.pdf";
String destFileName = desdirectry+"\\"+newfilename;

FileInputStream fstream = new FileInputStream(destFileName2);

// Get the object of DataInputStream

DataInputStream is = new DataInputStream(fstream);

 int read=0;
 byte[] bytes = new byte[BYTES_DOWNLOAD];
 OutputStream os = response.getOutputStream();
 
while((read = is.read(bytes))!= -1){
  os.write(bytes, 0, read);
 }
 os.flush();
 os.close(); 
   }
}
Let’s add the URL pattern in Web xml.

 ServletName
 com.osg.sqe.env.framework.control.web.MyServlet 

  
  ServletName
  /DownloadDemo
  
Finally we will place a hyperlink to our html page to initiate the download
http://localhost:port/modulename/DownloadDemo  

0 comments: