Thursday, May 5, 2011

PDF EXPORTER IN JAVA

PDFExporter for IceFaces


I noticed in the IceFaces forum a lot of people were having issues trying create an OutputTypeHandler for PDF Exporting.  Although I could of used Jasper reports to render the PDF, I decided to go with something fast that would not need dynamic report compiling.
Requirements:
IceFaces 1.8+
iText 2+

Since this is a handler and not a custom component you do not need to register any tags or renderers. The only requirement is a reference to the handler in your controller/managing bean and setting the tag to against IceFaces DataExporter component.
.jspx / .xhtml Syntax
1.<ICE:DATAEXPORTER outputTypeHandler="#{myBean.exporter}" type="pdf" label="Click to download PDF" for="dataExportTable" />

myBean.java
1....
2.public PDFExporter getExporter()
3.{
4.  return new PDFExporter();
5.}
6....
PDFExporter.java (Click “expand” below to view code)
01.package com.sourjuice;
02.  
03.import java.io.FileNotFoundException;
04.import java.io.FileOutputStream;
05.import java.util.ArrayList;
06.import com.icesoft.faces.component.dataexporter.OutputTypeHandler;
07.import com.lowagie.text.Document;
08.import com.lowagie.text.DocumentException;
09.import com.lowagie.text.Font;
10.import com.lowagie.text.FontFactory;
11.import com.lowagie.text.PageSize;
12.import com.lowagie.text.Paragraph;
13.import com.lowagie.text.pdf.PdfPTable;
14.import com.lowagie.text.pdf.PdfWriter;
15.public class PDFExporter extends OutputTypeHandler
16.{
17.    //Fonts to be used in PDF
18.    Font font = FontFactory.getFont("HELVETICA", "CP1254");
19.    Font headerFont = FontFactory.getFont("HELVETICA", "CP1254", Font.DEFAULTSIZE, Font.BOLD);
20.    PdfPTable pdfTable;
21.    Document document;
22.    ArrayList<STRING> headers;
23.  
24.    /*
25.     * This is a temporary constructor until IF 1.8.2 comes out with the public CoreUtils.getRealPath which is not in 1.8.1
26.     */
27.    public PDFExporter()
28.    {
29.           this(CoreUtils.getPathWithoutExtension() + ".pdf");
30.    }
31.  
32.    public PDFExporter(String filePath) {
33.        super(filePath);
34.        headers = new ArrayList<STRING>();
35.        try
36.        {
37.            document = new Document(PageSize.LETTER);
38.            document.setPageSize(PageSize.LETTER.rotate());
39.            PdfWriter.getInstance(document, new FileOutputStream(super.getFile()));
40.            document.open();
41.            this.mimeType = "application/pdf";
42.        }
43.        catch(DocumentException e){
44.            e.printStackTrace();
45.        } catch (FileNotFoundException e) {
46.            e.printStackTrace();
47.        }
48.  
49.    }
50.  
51.    @Override
52.    public void flushFile()
53.    {
54.        try
55.        {
56.            document.add(pdfTable);
57.            document.close();
58.        }
59.        catch (DocumentException e)
60.        {
61.            e.printStackTrace();
62.        }
63.    }
64.  
65.    public void createPDF()
66.    {
67.        pdfTable = new PdfPTable(headers.size());
68.  
69.        for (String header : headers)
70.        {
71.            pdfTable.addCell(new Paragraph(header, headerFont));
72.        }
73.    }
74.  
75.    @Override
76.    public void writeCell(Object output, int col, int row)
77.    {
78.        if (col == 0 && row == 0)
79.        {
80.            createPDF();
81.        }
82.        pdfTable.addCell(new Paragraph(output+"", font));
83.    }
84.  
85.    @Override
86.    public void writeHeaderCell(String text, int col)
87.    {
88.        // Since PDFTable needs exact header counts we are deferring rendering of the headers in this call
89.        headers.add(text);
90.    }
91.}
NOTE: If your using IceFaces 1.8.1 or prior you will need to create a CoreUtils class with the following code. This is so PDFExporter can find the proper path to the IceFaces resource servlet. These methods are currently in IceFace’s SVN and will be available in there next release. For now you can use the code below to get by.
**CoreUtils.java (Click “expand” below to view code)
01.package com.sourjuice;
02.  
03.import javax.faces.context.FacesContext;
04.import org.apache.commons.logging.Log;
05.import org.apache.commons.logging.LogFactory;
06.import java.io.File;
07.import java.lang.reflect.Constructor;
08.import java.lang.reflect.Method;
09.import java.util.Date;
10.  
11.public class CoreUtils
12.{
13.    private static Boolean portletEnvironment;
14.    private static final Log log = LogFactory.getLog(CoreUtils.class);
15.  
16.    public static String getPathWithoutExtension()
17.    {
18.        String path = getRealPath(FacesContext.getCurrentInstance(), "/export");
19.        File exportDir = new File(path);
20.        if (!exportDir.exists())
21.            exportDir.mkdirs();
22.        String pathWithoutExt = path + "/export_"
23.                + new Date().getTime();
24.        return pathWithoutExt;
25.    }
26.  
27.     public static String getRealPath(FacesContext facesContext, String path) {
28.            Object session = FacesContext
29.            .getCurrentInstance().getExternalContext().getSession(false);
30.            if (session == null) {
31.                log.error("getRealPath() session is null", new NullPointerException());
32.                return null;
33.            }
34.            if (isPortletEnvironment()) {
35.                return getRealPath(session, "getPortletContext", path);
36.            } else {
37.                return getRealPath(session, "getServletContext", path);
38.            }
39.        }
40.  
41.        private static String getRealPath(Object session, String getContext, String path) {
42.            try {
43.                Method getContextMethod = session.getClass().getMethod(getContext, null);
44.                Object context;
45.                context = getContextMethod.invoke(session, null);
46.                Class[] classargs = {String.class};
47.                Method getRealPath =  context.getClass().getMethod("getRealPath", classargs);
48.                Object[] args = {path};
49.                return String.valueOf(getRealPath.invoke(context, args));
50.            } catch (Exception e) {
51.                log.error("Error getting realpath", e);
52.                return null;
53.            }
54.        }
55.  
56.        public static boolean isPortletEnvironment() {
57.            if (portletEnvironment == null) {
58.                try {
59.                    portletEnvironment = new Boolean(FacesContext.getCurrentInstance().getExternalContext()
60.                            .getRequest() instanceof javax.portlet.PortletRequest);
61.                } catch (java.lang.NoClassDefFoundError e) {
62.                    //portlet not found
63.                    portletEnvironment = Boolean.FALSE;
64.                }
65.            }
66.            return portletEnvironment.booleanValue();
67.        }
68.}

No comments:

Post a Comment