Search code examples
javajasper-reportsrelative-path

Jasper Reports Change absolute path to relative path?


I am new to jasper, I want to compile the report in jrxml and export to pdf in from absolute path to relative path. Currently the codes work only in absolute path.

export to pdf = download folders of web browser jrxml inside the /Reports/ConsumptionReport.jrxml (inside the web pages) thank you :D

public void showReport(int productionNumber) throws JRException {

        try {




            DBConnectionFactory myFactory = DBConnectionFactory.getInstance();
            Connection conn = myFactory.getConnection();

            Map map = new HashMap();
            map.put("prodNum", productionNumber);

            JasperReport jr = JasperCompileManager.compileReport("/Users/user/NetBeansProjects/EGMI/web/Reports/ConsumptionReport.jrxml");
            //Fill the report with parameter, connection and the stream reader     
            JasperPrint jp = JasperFillManager.fillReport(jr, map, conn);

            JasperExportManager.exportReportToPdfFile(jp, "/Users/user/NetBeansProjects/EGMI/web/Reports/ConsumptionReport.pdf");
            JasperViewer.viewReport(jp, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

folder hierarchy

EGMI
   ---Web Pages
        ----Reports
               -----ConsumptionReport.jrxml 

SOLUTION- servlet

String relativeWebPath = "/Reports";
           String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
           File f = new File(absoluteDiskPath, "ConsumptionReport.jrxml");

Solution

  • Use java.io.File to get the absolute path from a relative path. es.

    File f = new File("yourRelativePath/ConsumptionReport.jrxml");
    JasperReport jr = JasperCompileManager.compileReport(f.getAbsolutePath());  
    

    Seeing the problem to find the relative path of your deployed web application I suggest you check out these questions.

    Need to find the web application path

    What does servletcontext.getRealPath("/") mean and when should I use it