หน้าเว็บ

วันศุกร์ที่ 5 กรกฎาคม พ.ศ. 2556

Export Jasper report to PDF file : java

maven project dependencies (pom.xml)
        ...
        ...
        ...

        <!-- Jasper Report **************************************************-->
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>5.0.1</version>
        </dependency>
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports-fonts</artifactId>
            <version>5.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>1.8.5</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
        </dependency>
        <!-- Jasper Report **************************************************-->

        ...
        ...
        ...
JasperUtils.java

package com.blogspot.na5cent.report;

import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.fill.JRFileVirtualizer;
import net.sf.jasperreports.engine.util.JRLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.blogspot.na5cent.util.JSFSpringUtils;

/**
 *
 * @author redcrow
 */
public class JasperUtils {

    private static final Logger LOG = LoggerFactory.getLogger(JasperUtils.class);
    private static Connection conn = null;

    public static void exportPDFToFile(JasperReport jasper, Object[] models, Map reportParam, File outputFile) throws JRException {
        JRFileVirtualizer virtualizer = null;
        try {
            //write report to temp file, protect out of memory
            virtualizer = new JRFileVirtualizer(2, System.getProperty("java.io.tmpdir"));
            reportParam.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
            
            //pass models into jasper bean   
            JRBeanArrayDataSource beans = new JRBeanArrayDataSource(models);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasper, reportParam, beans);

            //create exporter and set basic parameter
            JRPdfExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, outputFile);
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

            exporter.exportReport(); //export
        } finally {
            if (virtualizer != null) {
                virtualizer.cleanup(); //clean up temp file
            }
        }
    }

    public static void exportPDFToFile(InputStream jasperInputStream, Object[] models, Map reportParam, File outputFile) throws JRException {
        JasperReport jasper = (JasperReport) JRLoader.loadObject(jasperInputStream);
        exportPDFToFile(jasper, models, reportParam, outputFile);
    }

    public static void exportPDFToFileWithConnection(JasperReport jasper, Map reportParam, File outputFile, Connection connection) throws JRException {
        JRFileVirtualizer virtualizer = null;
        try {
            //write report to temp file, protect out of memory
            virtualizer = new JRFileVirtualizer(2, System.getProperty("java.io.tmpdir"));
            reportParam.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);

            //user connection (inject database connection into jasper report)
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasper, reportParam, connection);

            /create exporter and set basic parameter
            JRPdfExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, outputFile);
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

            exporter.exportReport(); //export
        } finally {
            if (virtualizer != null) {
                virtualizer.cleanup(); //clean up temp file
            }

            if (connection != null) {
                try {
                    connection.close(); //close database connection
                } catch (SQLException ex) {
                    LOG.warn(null, ex);
                }
            }
        }
    }

    public static void exportPDFToFileConnection(InputStream jasperInputStream, Map reportParam, File outputFile, Connection connection) throws JRException {
        JasperReport jasper = (JasperReport) JRLoader.loadObject(jasperInputStream);
        exportPDFToFileWithConnection(jasper, reportParam, outputFile, connection);
    }

    public static Connection getConnection(ServletContext servletContext) {
        try {

            if (conn == null || conn.isClosed()) {
                //Context ctx = new InitialContext();
                //DataSource ds = (DataSource) ctx.lookup("JNDI_NAME");
                //get datbase connection by spring util, you can learn at http://na5cent.blogspot.com/2012/12/jsf-get-service-by-webapplicationcontex.html
                DataSource ds = JSFSpringUtils.getBean(servletContext, DataSource.class); 
                conn = ds.getConnection();
            }
            return conn;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    public static void closeConnection() throws SQLException {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
}

example to use
    private void report() {
        if (abtSelection != null) {
            InputStream jasperInputStream = null;
            try {
                //read jasper file from class path (OtherSorces of maven project)
                jasperInputStream = SearchManagedBean.class.getResourceAsStream("/report/formPrint.jasper");

                //get path file from config file (config.prpperties)
                File parent = new File(configProperties.getProperty("reportPath"));
                if (!parent.exists()) { //check file exists, if dose't exist create it and all sub folders
                    parent.mkdirs(); 
                }

                File pdfFile = new File(parent, report);
                pdfFile.deleteOnExit();

                List<ReportModel> reportModels = new ArrayList<ReportModel>();
                for (ABT abt : abtSelection) {
                    if (abt != null) {
                        ReportModel model = new ReportModel();
                        String title = abt.getBoss() + " " + abt.getName();
                        model.setDate(new Date());
                        model.setTitle(title);
                        reportModels.add(model);
                    }
                }

                ReportModel[] models = new ReportModel[reportModels.size()];
                models = reportModels.toArray(models);

                Map param = new HashMap();
                //read image as  BufferedImage, you can learn at http://na5cent.blogspot.com/2013/04/send-image-to-jasper-report-java.html 
                BufferedImage headerImage = ImageIO.read(SearchManagedBean.class.getResourceAsStream("/report/headerImage.jpg"));
                param.put("headerImage", headerImage);
                param.put(JRParameter.REPORT_LOCALE, Languages.TH_LOCALE);  //set report locale

                JasperUtils.exportPDFToFile(jasperInputStream, models, param, pdfFile); //***********
            } catch (JRException ex) {
                LOG.warn(null, ex);
            } catch (IOException ex) {
                LOG.warn(null, ex);
            } finally {
                if (jasperInputStream != null) {
                    try {
                        jasperInputStream.close();
                    } catch (IOException ex) {
                        LOG.warn(null, ex);
                    }
                }
            }
        }
    }

2 ความคิดเห็น:

  1. เจ่งมาก..มือใหม่ี ไม่ค่อยรู้เรืองเลย ..ฯ มีง่ายป่ะ เอ่ย ? ิอิอิ

    ตอบลบ
  2. มี แบบ ใช้ Hibernate ร่วมมั้ย ??

    ตอบลบ