Esempio n. 1
1
  private byte[] generaXls(List lista) throws JRException {
    Map<String, Object> params = new HashMap<>();
    JRXlsExporter exporter = new JRXlsExporter();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    JasperDesign jd =
        JRXmlLoader.load(
            this.getClass()
                .getResourceAsStream("/mx/edu/um/mateo/inventario/reportes/almacenes.jrxml"));
    JasperReport jasperReport = JasperCompileManager.compileReport(jd);
    JasperPrint jasperPrint =
        JasperFillManager.fillReport(jasperReport, params, new JRBeanCollectionDataSource(lista));
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, byteArrayOutputStream);
    exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
    exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
    exporter.setParameter(
        JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IS_COLLAPSE_ROW_SPAN, Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS, Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
    exporter.exportReport();
    byte[] archivo = byteArrayOutputStream.toByteArray();

    return archivo;
  }
  @Override
  public IFile exportToIFile(
      AFileResource res, ResourceDescriptor rd, String fkeyname, IProgressMonitor monitor)
      throws Exception {
    IFile f = super.exportToIFile(res, rd, fkeyname, monitor);
    if (f != null) {
      JasperReportsConfiguration jrConfig = res.getJasperConfiguration();
      if (jrConfig == null) {
        jrConfig = JasperReportsConfiguration.getDefaultJRConfig(f);
        res.setJasperConfiguration(jrConfig);
      } else jrConfig.init(f);
      try {
        JasperDesign jd = JRXmlLoader.load(jrConfig, f.getContents());
        setPropServerURL(res, jd);
        setPropReportUnit(res, jd);
        getResources(res, jd);

        MServerProfile sp = (MServerProfile) res.getRoot();
        if (sp != null)
          f.setContents(
              new ByteArrayInputStream(
                  JRXmlWriterHelper.writeReport(null, jd, sp.getValue().getJrVersion())
                      .getBytes("UTF-8")),
              IFile.KEEP_HISTORY | IFile.FORCE,
              monitor);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    if (f != null) f.setPersistentProperty(KEY_REPORT_ISMAIN, Boolean.toString(rd.isMainReport()));
    return f;
  }
  @SuppressWarnings("unchecked")
  @EventListener
  public void apply(RichiestaServizioApprovata event) throws JRException, IOException {

    // Genero il report
    RichiestaNuovoServizioView uv =
        (RichiestaNuovoServizioView)
            sessionFactory
                .getCurrentSession()
                .createQuery("from RichiestaNuovoServizioView where richiestanuovoservizioId = :id")
                .setParameter("id", event.getId())
                .uniqueResult();

    List<RichiestaNuovoServizioView> data1 = new ArrayList<RichiestaNuovoServizioView>();
    data1.add(uv);
    JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(data1);

    InputStream inputStream = this.getClass().getResourceAsStream("report_richiesta.jrxml");

    @SuppressWarnings("rawtypes")
    Map parameters = new HashMap();

    parameters.put("logo", ImageIO.read(getClass().getResource("RAI_logo.png")));
    parameters.put("idRichiesta", event.getId().toString());

    JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

    JasperPrint jasperPrint =
        JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);

    String nomeFile = "report_" + event.getId().toString() + "_approvato.pdf";
    new java.io.File("static_assets/files/").mkdirs();
    JasperExportManager.exportReportToPdfFile(jasperPrint, "static_assets/files/" + nomeFile);
  }
  public void Generar_Contabilidad(Date Fecha_1, Date Fecha_2) {
    String JXML = "iReports\\Mini_contabilidad.jrxml";
    JasperPrint jasperPrint = null;
    InputStream inputStream = null;
    Map<String, Object> parametros;

    parametros = new HashMap<String, Object>();
    parametros.put("SD_fecha_1", Fecha_1);
    parametros.put("SD_fecha_2", Fecha_2);
    parametros.put("PD_fecha_pedido1", Fecha_1);
    parametros.put("PD_fecha_pedido2", Fecha_2);

    try {
      inputStream = new FileInputStream(JXML);
      JasperDesign jasperDesing = JRXmlLoader.load(inputStream);
      JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesing);

      ConectorMySQL con = new ConectorMySQL();
      con.connectToMySQL();
      jasperPrint = JasperFillManager.fillReport(jasperReport, parametros, con.conexion);

      con.cerrarConexion();
    } catch (JRException | FileNotFoundException e) {
      JOptionPane.showMessageDialog(
          null, "Error al leer el fichero de carga jasper report " + e.getMessage());
    }

    // MOSTRAR REPORTE
    JasperViewer view = new JasperViewer(jasperPrint, false);
    view.setTitle("Mini Contabilidad");
    view.setVisible(true);
  }
Esempio n. 5
0
  public static JasperReport tryJasperCache(String cs)
      throws CitationStyleManagerException, IOException, JRException {
    Utils.checkName(cs, "Empty style name.");

    JasperReport jr = XmlHelper.jasperCache.get(cs);

    if (jr == null) {

      // get default JasperDesign

      String path = CitationUtil.getPathToCitationStyles() + "citation-style.jrxml";
      JasperDesign jd =
          JRXmlLoader.load(
              ResourceUtil.getResourceAsStream(path, XmlHelper.class.getClassLoader()));

      // populate page header
      // setPageHeader(jd, cs);

      // set default Report Style
      setDefaultReportStyle(jd, cs);

      // compile to the JasperReport
      jr = JasperCompileManager.compileReport(jd);

      XmlHelper.jasperCache.put(cs, jr);
    }

    return jr;
  }
  /**
   * Compiles the XML report design file specified by the parameter. The result of this operation is
   * another file that will contain the serialized {@link net.sf.jasperreports.engine.JasperReport}
   * object representing the compiled report design, having the same name as the report design as
   * declared in the XML plus the <code>*.jasper</code> extension, located in the same directory as
   * the XML source file.
   *
   * @param sourceFileName XML source file name
   * @return resulting file name containing a serialized {@link
   *     net.sf.jasperreports.engine.JasperReport} object
   */
  public static String compileReportToFile(String sourceFileName) throws JRException {
    File sourceFile = new File(sourceFileName);

    JasperDesign jasperDesign = JRXmlLoader.load(sourceFileName);

    File destFile = new File(sourceFile.getParent(), jasperDesign.getName() + ".jasper");
    String destFileName = destFile.toString();

    compileReportToFile(jasperDesign, destFileName);

    return destFileName;
  }
Esempio n. 7
0
  private byte[] generaPdf(List lista) throws JRException {
    Map<String, Object> params = new HashMap<>();
    JasperDesign jd =
        JRXmlLoader.load(
            this.getClass()
                .getResourceAsStream("/mx/edu/um/mateo/inventario/reportes/almacenes.jrxml"));
    JasperReport jasperReport = JasperCompileManager.compileReport(jd);
    JasperPrint jasperPrint =
        JasperFillManager.fillReport(jasperReport, params, new JRBeanCollectionDataSource(lista));
    byte[] archivo = JasperExportManager.exportReportToPdf(jasperPrint);

    return archivo;
  }
Esempio n. 8
0
  private void jbtImprimirActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jbtImprimirActionPerformed
    ProdutoDaVendaDAO dao = new ProdutoDaVendaDAOIMPL();
    try {
      List<ProdutosDaVenda> dados = dao.buscarParametroParaImpressao(venda.getCodigo());
      JRDataSource datasource = new JRBeanCollectionDataSource(dados);
      JasperDesign jasper = JRXmlLoader.load("src/REPORT/Venda.jrxml");
      JasperReport jasperReport = JasperCompileManager.compileReport(jasper);
      JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, datasource);
      JasperViewer.viewReport(jasperPrint, false);

    } catch (JRException ex) {
      System.out.println("Filtro não encontrado" + ex.getMessage());
    }
  } // GEN-LAST:event_jbtImprimirActionPerformed
Esempio n. 9
0
 private static JasperDesign createJasperDesign(InputStream reportFile, GridReportVO gridReportVO)
     throws JRException {
   JasperDesign jasperDesign = JRXmlLoader.load(reportFile);
   if (log4j.isDebugEnabled()) log4j.debug("Create JasperDesign");
   ReportDesignBO designBO = new ReportDesignBO(jasperDesign, gridReportVO);
   designBO.define();
   if (log4j.isDebugEnabled())
     log4j.debug(
         "JasperDesign created, pageWidth: "
             + jasperDesign.getPageWidth()
             + " left margin: "
             + jasperDesign.getLeftMargin()
             + " right margin: "
             + jasperDesign.getRightMargin());
   return jasperDesign;
 }
Esempio n. 10
0
  private byte[] generaCsv(List lista) throws JRException {
    Map<String, Object> params = new HashMap<>();
    JRCsvExporter exporter = new JRCsvExporter();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    JasperDesign jd =
        JRXmlLoader.load(
            this.getClass()
                .getResourceAsStream("/mx/edu/um/mateo/inventario/reportes/almacenes.jrxml"));
    JasperReport jasperReport = JasperCompileManager.compileReport(jd);
    JasperPrint jasperPrint =
        JasperFillManager.fillReport(jasperReport, params, new JRBeanCollectionDataSource(lista));
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, byteArrayOutputStream);
    exporter.exportReport();
    byte[] archivo = byteArrayOutputStream.toByteArray();

    return archivo;
  }
  /**
   * @param m
   * @param report
   */
  public DepartmentItem(Map m, String report) {
    param = m;
    initConnection();
    try {
      InputStream file = DepartmentItem.class.getResource(report).openStream();
      jDesign = JRXmlLoader.load(file);
      // compi
      jReport = JasperCompileManager.compileReport(jDesign);
      // fill report
      jPrint = JasperFillManager.fillReport(jReport, this.param, conn);

      new ReportView(jPrint, "Complementary Report");
    } catch (JRException | IOException ex) {
      JOptionPane.showMessageDialog(null, "report.complementary.Complementary.contructor():" + ex);
    } finally {
      closeConnection();
    }
  }
Esempio n. 12
0
  public static void main(String[] args) {
    // - Paramètres de connexion à la base de données

    Connection connection;
    try {
      // - Connexion à la base
      connection = MyConnection.getInstance();
      // - Chargement et compilation du rapport (charger le fichier jrxml déjà généré)
      JasperDesign jasperDesign = JRXmlLoader.load("/pdf/report.jrxml");
      JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
      // - Paramètres à envoyer au rapport
      Map parameters = new HashMap();
      parameters.put("Titre", "Titre");
      // - Execution du rapport
      JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, connection);
      // - Création du rapport au format PDF
      JasperExportManager.exportReportToPdfFile(jasperPrint, "report.pdf");
      System.out.println("success");
    } catch (JRException e) {
      System.out.println("erreur de compilation" + e.getMessage());
    }
  }
Esempio n. 13
0
  public JasperPrint prepareJasper(
      List<StockOpnameDetail> stockOpnameDetails, Timestamp beginTimestamp, Timestamp endTimestamp)
      throws AppException {

    Map<String, Object> paramReport = new HashMap<String, Object>();
    paramReport.put("reportName", REPORT_NAME);
    paramReport.put("companyName", Main.getCompany().getName());
    paramReport.put("performedByUserName", Main.getUserLogin().getName());
    paramReport.put("performedBeginTimestamp", beginTimestamp);
    paramReport.put("performedEndTimestamp", endTimestamp);

    InputStream inputStream = null;
    try {
      inputStream = this.getClass().getClassLoader().getResourceAsStream(REPORT_FILE);

      JasperDesign jasperDesign = JRXmlLoader.load(inputStream);

      JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

      JasperPrint jasperPrint =
          JasperFillManager.fillReport(
              jasperReport, paramReport, new JRBeanCollectionDataSource(stockOpnameDetails));

      return jasperPrint;
    } catch (JRException e) {
      throw new AppException(e);
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          throw new AppException(e);
        }
      }
    }
  }
Esempio n. 14
0
  /**
   * Compiles the serialized report design object read from the supplied input stream and returns
   * the generated compiled report design object.
   *
   * @param inputStream XML source input stream
   * @return compiled report design object
   */
  public static JasperReport compileReport(InputStream inputStream) throws JRException {
    JasperDesign jasperDesign = JRXmlLoader.load(inputStream);

    return compileReport(jasperDesign);
  }
Esempio n. 15
0
  private void create_bottonActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_create_bottonActionPerformed
    // TODO add your handling code here:
    try {
      /*
          Connection conn =  DriverManager.getConnection("jdbc:sqlite:C:/Documents and Settings/ishant0/bonafide.db");

         JasperDesign jasperDesign = JRXmlLoader.load("E:\\PD\\pd\\pratice\\Bonafide\\src\\bonafide\\report1.jrxml");
         String name = Second.getcdt();
         //System.out.print(name);
         String sql = "select * from firstInfo order by date DESC LIMIT 1";


         /*java.util.Map parameters = new java.util.HashMap();
         parameters.put("name", name);
         String abc = "Hey now please work properly!!";
         parameters.put("abc", abc);
          *


         JRDesignQuery newQuery = new JRDesignQuery();
         newQuery.setText(sql);
         jasperDesign.setQuery(newQuery);
         JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
         JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, conn);
         JasperViewer.viewReport(jasperPrint);

      }
      catch (Exception ex)
      {
          JOptionPane.showMessageDialog(null, ex);
      }
       */

      // Commented on 18-june-2013
      /*
        ps = con.prepareStatement("select * from abc"); //Table abc contains formate for certificates..............
        /* now use type table with typeName and formate datafield.....
         *

        rs = ps.executeQuery();
        rs.next();
        String s = rs.getString(1);

            rs.close();
            ps.close();



        st = con.createStatement();
        ResultSet rs2= st.executeQuery("select * from firstInfo order by date desc limit 1");
        rs2.next();
        String name = rs2.getString("name");
        String rollnum = rs2.getString("rollnum");



        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(java.util.regex.Pattern.quote("name??"));
        String data[] = pattern.split(s);
        String o1 = data[0] +" "+name+" "+data[1];

        pattern = java.util.regex.Pattern.compile(java.util.regex.Pattern.quote("roll??"));
        data = pattern.split(o1);
        String op = data[0] +" "+rollnum+" "+data[1];
        //System.out.println(op);

      */

      // NWE CODE:
      // Step-1  Fetching formate from type table.
      try {
        con = Connect.getConnection();

        ps = con.prepareStatement("select formate from type where typeName = 'Student Bonafide'");
        rs = ps.executeQuery();
        if (rs.next()) {
          formate = rs.getString("formate");
        } else {
          javax.swing.JOptionPane.showMessageDialog(
              null, "Internal error formate type or Certificate type not found.");
        }

        Connect.closeConnection(con, ps, rs);
        System.out.println("Step 1 completed!!!");
      } catch (Exception e) {
        javax.swing.JOptionPane.showMessageDialog(null, "Closing rs or ps for step 1" + e);
      }

      // Step-2 Fetching data which is last entered in firstInfo table.
      try {
        con = Connect.getConnection();

        ps = con.prepareStatement("select * from firstInfo order by date desc limit 1");
        java.sql.ResultSet rs2 = ps.executeQuery();
        rs2.next();
        name = rs2.getString("name");
        rollnum = rs2.getString("rollnum");
        father_name = rs2.getString("father_name");
        course = rs2.getString("course");
        semester = rs2.getString("sem");

        // System.out.println(name+rollnum+father_name);
        Connect.closeConnection(con, ps, rs2);
        System.out.println("Step 2 completed!!!");
      } catch (Exception e) {
        javax.swing.JOptionPane.showMessageDialog(null, "Problem in step 2" + e);
      }

      // Step-3 Merging data with formate
      try {
        to_deliver = Connect.splitJoin(formate, "{name}", name);
        to_deliver = Connect.splitJoin(to_deliver, "{roll}", rollnum);
        to_deliver = Connect.splitJoin(to_deliver, "(father}", father_name);
        to_deliver = Connect.splitJoin(to_deliver, "{course}", course);
        to_deliver = Connect.splitJoin(to_deliver, "{semester}", semester);
        System.out.println(to_deliver);
        System.out.println("Step 3 completed!!!");
      } catch (Exception e) {
        javax.swing.JOptionPane.showMessageDialog(null, "Problem while merging!" + e);
      }

      // Sending this above result op to toDeliver table:
      try {
        con = Connect.getConnection();
        ps = con.prepareStatement("insert into toDeliver (op) values(?)");
        ps.setString(1, to_deliver);
        ps.executeUpdate();
        Connect.closeConnection(con, ps, null);
      } catch (Exception e) {
        javax.swing.JOptionPane.showMessageDialog(null, "Problem in delivering data" + e);
      }

      // Now code for jasper reports:
      Connection conn =
          DriverManager.getConnection("jdbc:sqlite:C:/Documents and Settings/ishant0/bonafide.db");
      JasperDesign jasperDesign =
          JRXmlLoader.load("E:\\PD\\pd\\pratice\\Bonafide\\src\\bonafide\\report1.jrxml");
      String sql = "select * from toDeliver order by date DESC LIMIT 1";

      JRDesignQuery newQuery = new JRDesignQuery();
      newQuery.setText(sql);
      jasperDesign.setQuery(newQuery);
      JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
      JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, conn);
      JasperViewer.viewReport(jasperPrint);

      // con.close();

    } catch (Exception e) {
      javax.swing.JOptionPane.showMessageDialog(null, e);
    }
  } // GEN-LAST:event_create_bottonActionPerformed
Esempio n. 16
0
  /**
   * Compiles the XML report design file received as the first parameter, placing the result in the
   * file specified by the second parameter. The resulting file will contain a serialized instance
   * of a {@link net.sf.jasperreports.engine.JasperReport} object representing the compiled report
   * design.
   *
   * @param sourceFileName XML source file name
   * @param destFileName file name to place the result into
   */
  public static void compileReportToFile(String sourceFileName, String destFileName)
      throws JRException {
    JasperDesign jasperDesign = JRXmlLoader.load(sourceFileName);

    compileReportToFile(jasperDesign, destFileName);
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    try {
      System.out.println("Genetate Report");
      // Get requested student id from user request
      //	String studentId = request.getParameter("sid");

      // Get requested report type from user request
      String reportType = request.getParameter("reportType");

      // Setting Default report Type
      if (reportType == null || reportType.trim().length() == 0) {
        reportType = "pdf";
      }

      // Get servlet Out put stream to displat report at client side
      ServletOutputStream sos = response.getOutputStream();

      // Construct path for your .jrxml file
      ServletContext application = getServletContext();
      String prefix = application.getRealPath("\\");
      // String file = getInitParameter("reportTemplet");
      String file = "AveTechEventReport.jrxml";
      String path = prefix + file;

      System.out.println("Path : " + path);

      // Load that .jrxml file in Jasper Design
      JasperDesign jasperDesign = JRXmlLoader.load(path);

      // Compile that .jrxml file into .jasper file
      JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

      /* Populate data from your database It must contain all the fields used in designing a .jrxml file
         Here we have used Java Bean Data Source in generating report.
         So populate ArrayList which contains your collection of your beans.
      */

      JRBeanCollectionDataSource ds =
          new JRBeanCollectionDataSource(AdminDAO.getAllEventData(), false);

      // Filling the reports using your .jasper file and generated Java Bean Datasource
      JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, ds);

      // Response for generating PDF report
      if (reportType != null && reportType.equals("pdf")) {
        System.out.println("PDF");
        response.setContentType("application/pdf");
        JRPdfExporter expoterPDF = new JRPdfExporter();
        expoterPDF.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        expoterPDF.setParameter(JRExporterParameter.OUTPUT_STREAM, sos);
        expoterPDF.exportReport();
      }

      // Response for generating EXCEL report
      if (reportType != null && reportType.equals("excel")) {
        response.setContentType("application/vnd.ms-excel");
        JRXlsExporter exporterXLS = new JRXlsExporter();
        exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
        exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, sos);
        exporterXLS.exportReport();
      }

      // Response for generating WORD report
      if (reportType != null && reportType.equals("word")) {
        response.setContentType("application/msword");
        JRRtfExporter exporterRTF = new JRRtfExporter();
        exporterRTF.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporterRTF.setParameter(JRExporterParameter.OUTPUT_STREAM, sos);
        exporterRTF.exportReport();
      }

      // Closing all opened streams
      sos.flush();
      sos.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Esempio n. 18
0
  /**
   * Compiles the XML report design file received as parameter, and returns the compiled report
   * design object.
   *
   * @param sourceFileName XML source file name
   * @return compiled report design object
   */
  public static JasperReport compileReport(String sourceFileName) throws JRException {
    JasperDesign jasperDesign = JRXmlLoader.load(sourceFileName);

    return compileReport(jasperDesign);
  }
  public static File generate(HrReport report, String outputFormat, String jrxmlUrl)
      throws IOException {

    String url = Context.getRuntimeProperties().getProperty("connection.url", null);
    Connection conn;
    try {
      conn = connect(url);
    } catch (SQLException e) {
      log.error("Error connecting to DB.", e);
      return null;
    }
    Map<String, Object> map = new HashMap<String, Object>();
    for (HrReportParameter reportParameter : report.getParameters()) {
      if (reportParameter != null)
        if (reportParameter.getName() != null)
          map.put(reportParameter.getName(), reportParameter.getValue());
    }
    log.debug("Report parameter map: " + map);
    String exportPath = OpenmrsUtil.getApplicationDataDirectory();
    URL resourceUrl = new URL(jrxmlUrl);
    InputStream is = resourceUrl.openStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    FileWriter appDirJrxml = new FileWriter(new File(exportPath + report.getFileName()));
    BufferedWriter bw = new BufferedWriter(appDirJrxml);
    String line;
    while ((line = br.readLine()) != null) {
      bw.write(line);
      bw.write("\n");
    }
    bw.flush();
    bw.close();
    JasperPrint jasperPrint = null;
    try {
      JasperDesign jasperDesign = JRXmlLoader.load(exportPath + report.getFileName());
      JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
      jasperPrint = JasperFillManager.fillReport(jasperReport, map, conn);
      if (outputFormat.equals("PDF")) {
        File pdfFile =
            new File(
                exportPath
                    + report.getName()
                    + new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss").format(new Date())
                    + ".pdf");
        JasperExportManager.exportReportToPdfFile(jasperPrint, pdfFile.getAbsolutePath());
        return pdfFile;
      } else if (outputFormat.equals("Excel")) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        File outputfile =
            new File(
                exportPath
                    + report.getName()
                    + new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss").format(new Date())
                    + ".xls");
        OutputStream outputfileStream = new FileOutputStream(outputfile);
        JRXlsExporter exporterXLS = new JRXlsExporter();
        exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
        exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, output);
        exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
        exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
        exporterXLS.setParameter(
            JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
        exporterXLS.exportReport();
        outputfileStream.write(output.toByteArray());
        outputfileStream.flush();
        outputfileStream.close();
        return outputfile;
      }
    } catch (JRException e) {
      log.error("Error generating report", e);
    } finally {
      try {
        if (!conn.isClosed()) {
          conn.close();
        }
      } catch (SQLException e) {
        log.error("Exception closing report connection.", e);
      }
    }
    return null;
  }
Esempio n. 20
0
  /**
   * Compiles the XML representation of the report design read from the supplied input stream and
   * writes the generated compiled report design object to the output stream specified by the second
   * parameter.
   *
   * @param inputStream XML source input stream
   * @param outputStream output stream to write the compiled report design to
   */
  public static void compileReportToStream(InputStream inputStream, OutputStream outputStream)
      throws JRException {
    JasperDesign jasperDesign = JRXmlLoader.load(inputStream);

    compileReportToStream(jasperDesign, outputStream);
  }