コード例 #1
4
  public void viewReport(String text, JTabbedPane pnl, int year) {

    sid = Integer.parseInt(text);
    if (text.equals("")) {
      JOptionPane.showMessageDialog(repstu, "Type the Student Id");
    } else {

      String rep_path = System.getProperty("user.dir") + "/reports/payment_stu.jrxml";
      Map<String, Object> params = new HashMap<String, Object>();

      params.put("sid", sid);
      params.put("year", "" + year);
      params.put("name", this.getName());
      params.put("datetime", this.getDateTime());

      try {

        JasperReport jreport = JasperCompileManager.compileReport(rep_path);
        JasperPrint jprint = JasperFillManager.fillReport(jreport, params, DB.getmyCon());

        JRViewer jview = new JRViewer(jprint);
        pnl.removeAll();
        pnl.add("Report", jview);

        jview.setZoomRatio((float) 0.9);
      } catch (Exception ex) {
        System.out.println("ERROR:" + ex);
      }
    }
  }
コード例 #2
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;
  }
コード例 #3
0
ファイル: Utilitaires.java プロジェクト: bianconejo/CEFX
  public static JasperPrint generateRecapAdressesClients(Date dateDebut, Date dateFin) {

    JasperPrint printImprCheques = new JasperPrint();

    Connection conn = null;
    long start = System.currentTimeMillis();
    try {

      Map<String, Object> paramFacture = new HashMap<String, Object>();
      paramFacture.put("debut", dateDebut);
      paramFacture.put("fin", dateFin);

      org.hibernate.Session session = CEFXUtil.getSessionFactory().getCurrentSession();

      SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
      ConnectionProvider cp = sfi.getConnectionProvider();
      conn = cp.getConnection();

      printImprCheques =
          JasperFillManager.fillReport("src/cefx/report/AdresseAnnee.jasper", paramFacture, conn);

    } catch (Exception e) {
      throw new RuntimeException("Impossible de générer le recap", e);
    } finally {
      //                     it's your responsibility to close the connection, don't forget it!
      if (conn != null) {
        try {
          conn.close();
        } catch (Exception e) {
        }
      }
    }

    return printImprCheques;
  }
コード例 #4
0
ファイル: ReportManager.java プロジェクト: s-chand/clients
  /**
   * Generates and displays <b>BA Unit</b> report.
   *
   * @param appBean Application bean containing data for the report.
   */
  public static JasperPrint getLodgementReport(
      LodgementBean lodgementBean, Date dateFrom, Date dateTo) {
    HashMap inputParameters = new HashMap();
    Date currentdate = new Date(System.currentTimeMillis());
    inputParameters.put("REPORT_LOCALE", Locale.getDefault());

    inputParameters.put("CURRENT_DATE", currentdate);

    inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
    inputParameters.put("FROMDATE", dateFrom);
    inputParameters.put("TODATE", dateTo);
    LodgementBean[] beans = new LodgementBean[1];
    beans[0] = lodgementBean;
    JRDataSource jds = new JRBeanArrayDataSource(beans);
    try {
      return JasperFillManager.fillReport(
          ReportManager.class.getResourceAsStream("/reports/LodgementReportSamoa.jasper"),
          inputParameters,
          jds);
    } catch (JRException ex) {
      LogUtility.log(LogUtility.getStackTraceAsString(ex), Level.SEVERE);
      MessageUtility.displayMessage(
          ClientMessage.REPORT_GENERATION_FAILED, new Object[] {ex.getLocalizedMessage()});
      return null;
    }
  }
コード例 #5
0
ファイル: ReportManager.java プロジェクト: s-chand/clients
 /** Generates and displays <b>BR VAlidaction Report</b>. */
 public static JasperPrint getBrValidaction() {
   HashMap inputParameters = new HashMap();
   inputParameters.put("REPORT_LOCALE", Locale.getDefault());
   inputParameters.put("today", new Date());
   inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getUserName());
   BrListBean brList = new BrListBean();
   brList.FillBrs();
   int sizeBrList = brList.getBrBeanList().size();
   BrReportBean[] beans = new BrReportBean[sizeBrList];
   for (int i = 0; i < sizeBrList; i++) {
     beans[i] = brList.getBrBeanList().get(i);
   }
   JRDataSource jds = new JRBeanArrayDataSource(beans);
   try {
     return JasperFillManager.fillReport(
         ReportManager.class.getResourceAsStream("/reports/BrValidaction.jasper"),
         inputParameters,
         jds);
   } catch (JRException ex) {
     LogUtility.log(LogUtility.getStackTraceAsString(ex), Level.SEVERE);
     MessageUtility.displayMessage(
         ClientMessage.REPORT_GENERATION_FAILED, new Object[] {ex.getLocalizedMessage()});
     return null;
   }
 }
コード例 #6
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  private byte[] gerarRelatorioJasperXLS(JasperReport nomeJasper, Map parametros, JRDataSource ds)
      throws JRException, IOException {

    JasperPrint jasperPrint = JasperFillManager.fillReport(nomeJasper, parametros, ds);
    JExcelApiExporter xlsExporter = new JExcelApiExporter();
    ByteArrayOutputStream xlsReport = new ByteArrayOutputStream();

    xlsExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    xlsExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, xlsReport);
    xlsExporter.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS, Boolean.TRUE);
    xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
    xlsExporter.setParameter(JRXlsExporterParameter.IS_IGNORE_GRAPHICS, Boolean.TRUE);
    xlsExporter.setParameter(
        JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
    xlsExporter.setParameter(
        JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE);
    xlsExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
    // Parametro que remove campos em branco quando um campo ocupa mais de uma linha e os outros não
    xlsExporter.setParameter(JRXlsExporterParameter.IS_COLLAPSE_ROW_SPAN, Boolean.TRUE);

    xlsExporter.exportReport();
    xlsReport.close();

    return xlsReport.toByteArray();
  }
コード例 #7
0
  JasperPrint createReport(
      Pair<LocalDate, LocalDate> interval,
      AgentOrgSocProtect supervisor,
      AgentRecipient beneficiary)
      throws JRException, URISyntaxException {

    Map<String, Object> params = new HashMap<>();
    params.put(
        JRParameter.REPORT_RESOURCE_BUNDLE,
        ResourceBundle.getBundle(
            "Bundle", FacesContext.getCurrentInstance().getViewRoot().getLocale()));
    params.put(
        JRParameter.REPORT_LOCALE, FacesContext.getCurrentInstance().getViewRoot().getLocale());
    params.put("REPORT_LOCALE", FacesContext.getCurrentInstance().getViewRoot().getLocale());
    params.put("REPORT_TITLE", reportTitle);
    params.put("BEGIN_DATE", YearMonth.from(interval.getLeft()));
    params.put("END_DATE", YearMonth.from(interval.getRight()));
    params.put("UNDERSIGNED", undersigned);

    List<ReportEntry> entries =
        repository.findPaymentsBy(persistenceUnitName, interval, supervisor, beneficiary);
    entries.addAll(
        repository.findRefundsBy(persistenceUnitName, interval, supervisor, beneficiary));

    if (displayPeriodGaps) {
      entries = fillForEmptyPeriods(entries, interval);
    }

    final String template =
        resourceLocator.getAbsolutePathToResource(
            "jasperreports/LegacyChernobylBeneficiaryPayments.jrxml");

    JasperReport report = JasperCompileManager.compileReport(template);
    return JasperFillManager.fillReport(report, params, new JRBeanCollectionDataSource(entries));
  }
コード例 #8
0
  public static void imprimeRelatorio(String nomeRelatorio, HashMap parametros, List lista) {
    try {
      JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(lista);
      FacesContext facesContext = FacesContext.getCurrentInstance();
      ServletContext servletContext =
          (ServletContext) facesContext.getExternalContext().getContext();
      String path = servletContext.getRealPath("/WEB-INF/relatorios/");
      // parametro jasper report
      parametros.put("SUBREPORT DIR", path + File.separator);
      JasperPrint jasperPrint =
          JasperFillManager.fillReport(
              servletContext.getRealPath("/WEB-INF/relatorios/")
                  + File.separator
                  + nomeRelatorio
                  + ".jasper",
              parametros,
              dataSource);
      byte[] b = JasperExportManager.exportReportToPdf(jasperPrint);

      HttpServletResponse res =
          (HttpServletResponse) facesContext.getExternalContext().getResponse();
      res.setContentType("application/pdf");
      int codigo = (int) (Math.random() * 1000);
      res.setHeader("Content-disposition", "inline);filename-relatorio_" + codigo + ".pdf");
      res.getOutputStream().write(b);
      facesContext.responseComplete();

    } catch (Exception e) {
      UtilMensagens.mensagemErro("Erro ao imprimir: " + UtilErros.getMensagemErro(e));
      e.printStackTrace();
    }
  }
コード例 #9
0
ファイル: RelatorioDAO.java プロジェクト: benyAlves/moteljava
 public JasperPrint relatorioModalidade(String modalidade) throws Exception {
   java.sql.Connection con = ConexaoDB.getInstance().getCon();
   String nomeRelatorio = "br/sistcomp/sar/impressao/relatorioModalidade.jasper";
   URL urlFile = getClass().getClassLoader().getResource(nomeRelatorio);
   modalidade = (new StringBuilder()).append("= '").append(modalidade).append("'").toString();
   String query =
       (new StringBuilder())
           .append(
               "SELECT p.nome,a.matricula,m.nome "
                   + "AS modalidade FROM pessoas p INNER JOIN alunos a ON p.idPessoa = a.idPessoa"
                   + " INNER JOIN adesoes ad ON a.matricula = ad.matricula INNER JOIN planos pl on "
                   + "ad.codPlano = pl.`codPlano` INNER JOIN modalidades m ON pl.codModalidade = "
                   + "m.codModalidade WHERE m.nome ")
           .append(modalidade)
           .append(" ")
           .append(" ORDER BY p.nome")
           .toString();
   PreparedStatement stmt = (PreparedStatement) con.prepareStatement(query);
   ResultSet rs = stmt.executeQuery();
   JRResultSetDataSource jrRS = new JRResultSetDataSource(rs);
   java.util.Map parameters = new HashMap();
   JasperPrint rel = JasperFillManager.fillReport(urlFile.openStream(), parameters, jrRS);
   rs.close();
   stmt.close();
   return rel;
 }
コード例 #10
0
  //    public void init(){
  //        JRBeanCollectionDataSource beanCollectionSource=new
  // JRBeanCollectionDataSource(order.getShoppingCart().getShoppingCartItems());
  //        JasperFillManager.fillReport(null, null)
  //    }
  //
  //
  public void generateInvoicePDF(int orderId) throws JRException, IOException {

    order = purchaseOrderService.findById(orderId);

    // EntityManager em=PerisitenceManager.getEntityManager();
    // Query query= em.createQuery("select s from ShoppingCart s");
    // List<shoppingcart> listOfShoppingCart=(List<shoppingcart>)query.getResultList();
    Map<String, Object> param = new HashMap<String, Object>();

    param.put("invoiceNumber", String.valueOf(order.getId()));
    param.put("customerName", order.getUser().getFirstName() + order.getUser().getLastName());

    List<ShoppingCartItem> items = order.getShoppingCart().getShoppingCartItems();
    JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(items);
    String reportPath =
        FacesContext.getCurrentInstance()
            .getExternalContext()
            .getRealPath("/jsfpages/reports/invoice.jasper");
    JasperPrint jasperPrint;
    jasperPrint = JasperFillManager.fillReport(reportPath, param, beanCollectionDataSource);
    HttpServletResponse httpServletResponse =
        (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
    ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
    JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
    FacesContext.getCurrentInstance().responseComplete();
  }
コード例 #11
0
  private JasperPrint runAndRender(Report report) throws Exception, JRException {
    JasperPrint jasperPrint = new JasperPrint();

    JasperReport jasperReport =
        JasperCompileManager.compileReport(
            System.getProperty("opennms.home")
                + File.separator
                + "etc"
                + File.separator
                + "report-templates"
                + File.separator
                + report.getReportTemplate());

    if (report.getReportEngine().equals("jdbc")) {
      Connection connection = DataSourceFactory.getDataSource().getConnection();
      jasperPrint =
          JasperFillManager.fillReport(
              jasperReport, paramListToMap(report.getParameterCollection()), connection);
      connection.close();
    } else if (report.getReportEngine().equals("opennms")) {
      LogUtils.errorf(this, "Sorry the OpenNMS Data source engine is not yet available");
      jasperPrint = null;
    } else {
      LogUtils.errorf(this, "Unknown report engine: %s ", report.getReportEngine());
      jasperPrint = null;
    }

    return jasperPrint;
  }
コード例 #12
0
ファイル: JasperLinkService.java プロジェクト: jcai/corner2
  /**
   * @param jasperInStream 获取打印对象的流
   * @param parameters 报表的参数
   * @return
   * @throws JRException
   */
  @SuppressWarnings("unchecked")
  protected JasperPrint getJasperPrint(
      InputStream jasperInStream,
      IPage page,
      Map parameters,
      String detailEntity,
      String detailCollection,
      int pageNumber)
      throws JRException {
    // 如果要传递参数(子报表等)
    if (page instanceof IJasperParameter) {
      Map param = ((IJasperParameter) page).getJasperParameters();
      if (param.size() != 0) {
        for (Iterator i = (Iterator) param.keySet().iterator(); i.hasNext(); ) {
          String key = (String) i.next();
          parameters.put(key, param.get(key));
        }
      }
    }
    // 前边已填充报表则设置参数到报表
    if (pageNumber > 0) {
      parameters.put(PAGE_NUMBER_ADD, pageNumber);
    }
    if (parameters.containsKey(MAIN_REPORT)) {
      jasperInStream = (InputStream) parameters.get(MAIN_REPORT);
    }

    return JasperFillManager.fillReport(
        jasperInStream, parameters, getDataSource(page, detailCollection, detailEntity));
  }
コード例 #13
0
  public acompanhamentoInci() {
    try {

      conInci.conecta();
      conInci.executeSQL(
          "select * from incineracao where (id_maquina = "
              + acompanhamentoPesagemIncineracaoAux.maquina
              + ") and (turno_incineracao = "
              + acompanhamentoPesagemIncineracaoAux.turno
              + ") and (data_incineracao between '"
              + acompanhamentoPesagemIncineracaoAux.periodoInicial
              + "' and '"
              + acompanhamentoPesagemIncineracaoAux.periodoFinal
              + "') and (tipo_residuo = "
              + acompanhamentoPesagemIncineracaoAux.residuo
              + ") and (situacao_reg = 'G') order by "
              + acompanhamentoPesagemIncineracaoAux.ordenacao);
      JRResultSetDataSource jrRS = new JRResultSetDataSource(conInci.resultset);
      JasperPrint jasperPrint =
          JasperFillManager.fillReport(
              "RelatoriosArqJasper/acompanhaInci.jasper", new HashMap(), jrRS);

      JasperViewer.viewReport(jasperPrint, false);

      // desconecta
      conInci.desconecta();

    } catch (Exception erro) {
      JOptionPane.showMessageDialog(null, "deu erro =" + erro);
      // desconecta
      conInci.desconecta();
    }
  }
コード例 #14
0
  @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);
  }
コード例 #15
0
  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);
  }
コード例 #16
0
ファイル: Pagamento.java プロジェクト: jdruk/legado-raquel
  private void jButton3ActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton3ActionPerformed
    String arquivo = "C:/projeto/service/selfservice/relatorio/relRecibo.jasper";
    Map<String, Object> map = new HashMap<>();
    map.put("VENDA", jtCodigo.getText());
    map.put("VALORTOTAL", jtTotalVenda.getText());
    map.put("FALTA", jtFalta.getText());
    String pago =
        String.valueOf(
            Math.abs(
                Double.parseDouble(jtFalta.getText())
                    - Double.parseDouble(jtTotalVenda.getText())));
    map.put("PAGO", pago);

    //        System.out.println(map);
    try {
      JasperReport jasperReport;
      Connection con;
      JasperPrint jasperPrint;
      jasperReport = (JasperReport) JRLoader.loadObject(arquivo);
      con = DriverManager.getConnection("jdbc:odbc:service", "", "");
      jasperPrint = JasperFillManager.fillReport(jasperReport, map, con);
      JasperViewer jrviewer = new JasperViewer(jasperPrint, false);
      jrviewer.setVisible(true);
    } catch (JRException | SQLException ex) {
      JOptionPane.showMessageDialog(null, ex.getMessage());
    }
  } // GEN-LAST:event_jButton3ActionPerformed
コード例 #17
0
 public void informe() {
   // try - para controlar las excepciones.
   try {
     // Iniciamos una transacción
     st.beginTransaction();
     // Obtenemos una lista de funcionario
     List<Funcionario> lista = (List<Funcionario>) st.createQuery("From Funcionario").list();
     // Utilizamos el método siguiente para cargar el reporte "FuncionarioReport.jasper"
     // El "JRLoader.loadObject" es el cargador.
     JasperReport report =
         (JasperReport)
             JRLoader.loadObject(
                 ClassLoader.getSystemResource("com/informes/FuncionarioReport.jasper"));
     // El método siguiente nos permite pasarle los datos al reporte utilizando
     // JRBeanCollectionDataSource y como argumento la lista que creamos más arriba.
     // La lista posee los siguiente campos: "id" "nombres" "apellidos" "dir" "cargo" en
     // coincidencia con los de nuestro archivo de reporte.
     JasperPrint fillReport =
         JasperFillManager.fillReport(report, null, new JRBeanCollectionDataSource(lista));
     // El JasperViewer para visualizar, le pasamos como argumento nuestro "fillReport" de arriba.
     JasperViewer jviewer = new JasperViewer(fillReport, false);
     // Le damos un título al reporte.
     jviewer.setTitle("Lista de Funcionarios");
     // La hacemos visible.
     jviewer.setVisible(true);
   } catch (Exception e) {
     JOptionPane.showMessageDialog(null, "Error cargando reporte.");
   }
 }
コード例 #18
0
  public void SimpleReportDiretoPdf() {

    JasperPrint jp = null;
    try {

      JRDataSource customDs = new CustomBs();

      jp = JasperFillManager.fillReport(arq, null, customDs);

      JasperViewer jasperViewer = new JasperViewer(jp);

      jasperViewer.setBounds(50, 50, 320, 240);
      jasperViewer.setLocationRelativeTo(null);
      jasperViewer.setExtendedState(JFrame.MAXIMIZED_BOTH);

      jasperViewer.setVisible(true);

      JasperExportManager.exportReportToPdfFile(jp, OUT_PDF);

      JOptionPane.showMessageDialog(
          null,
          "<html>Arquivo exportado para PDF!<br><br>A aplicação vai pedir"
              + " ao Sistema operacional <br>para abrir com o visualizador"
              + " padrão.");

      Desktop.getDesktop().open(new File(OUT_PDF));

    } catch (JRException ex) {
      ex.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #19
0
  private void viewReport() throws Exception {
    Date fromDate = fromDatePicker.getDate();
    Date toDate = toDatePicker.getDate();

    if (fromDate.after(toDate)) {
      POSMessageDialog.showError(
          com.floreantpos.util.POSUtil.getFocusedWindow(),
          com.floreantpos.POSConstants.FROM_DATE_CANNOT_BE_GREATER_THAN_TO_DATE_);
      return;
    }

    fromDate = DateUtil.startOfDay(fromDate);
    toDate = DateUtil.endOfDay(toDate);

    ReportService reportService = new ReportService();
    JournalReportModel report = reportService.getJournalReport(fromDate, toDate);

    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("reportTitle", "========= JOURNAL REPORT ==========");
    map.put("fromDate", ReportService.formatShortDate(fromDate));
    map.put("toDate", ReportService.formatShortDate(toDate));
    map.put("reportTime", ReportService.formatFullDate(new Date()));

    JasperReport jasperReport = ReportUtil.getReport("journal_report");
    JasperPrint jasperPrint =
        JasperFillManager.fillReport(
            jasperReport, map, new JRTableModelDataSource(report.getTableModel()));
    JRViewer viewer = new JRViewer(jasperPrint);
    reportContainer.removeAll();
    reportContainer.add(viewer);
    reportContainer.revalidate();
  }
コード例 #20
0
ファイル: ReportManager.java プロジェクト: s-chand/clients
  /**
   * Generates and displays <b>Lodgement notice</b> report for the new application.
   *
   * @param appBean Application bean containing data for the report.
   */
  public static JasperPrint getLodgementNoticeReport(
      ApplicationBean appBean, boolean isProduction) {
    HashMap inputParameters = new HashMap();
    inputParameters.put("REPORT_LOCALE", Locale.getDefault());
    inputParameters.put("today", new Date());
    inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
    inputParameters.put("IS_PRODUCTION", isProduction);
    ApplicationBean[] beans = new ApplicationBean[1];
    beans[0] = appBean;
    JRDataSource jds = new JRBeanArrayDataSource(beans);
    inputParameters.put(
        "IMAGE_SCRITTA_GREEN",
        ReportManager.class.getResourceAsStream("/images/sola/govSamoa.gif"));
    inputParameters.put("WHICH_CALLER", "N");

    try {
      return JasperFillManager.fillReport(
          ReportManager.class.getResourceAsStream("/reports/ApplicationPrintingForm.jasper"),
          inputParameters,
          jds);
    } catch (JRException ex) {
      LogUtility.log(LogUtility.getStackTraceAsString(ex), Level.SEVERE);
      MessageUtility.displayMessage(
          ClientMessage.REPORT_GENERATION_FAILED, new Object[] {ex.getLocalizedMessage()});
      return null;
    }
  }
  public void runReporteVentasPorAnualContado(String fecha) {
    try {

      String master =
          System.getProperty("user.dir")
              + "/src/ComponenteReportes/ReporteVentasPorAnualContado.jasper";
      // System.out.println("master" + master);
      if (master == null) {
        System.out.println("no encuentro el archivo de reporte maestro");
        System.exit(2);
      }
      JasperReport masterReport = null;
      try {
        masterReport = (JasperReport) JRLoader.loadObject(master);
      } catch (JRException e) {
        System.out.println("error cargando el reporte maestro:" + e.getMessage());
        System.exit(3);
      }
      Map parametro = new HashMap();
      parametro.put("fecha", fecha);
      JasperPrint jasperPrint = JasperFillManager.fillReport(masterReport, parametro, cnn);
      JasperViewer jviewer = new JasperViewer(jasperPrint, false);
      jviewer.setTitle("REPORTE VENTAS A CONTADO ANUAL");
      jviewer.setVisible(true);
      cnn.close();
    } catch (Exception j) {
      System.out.println("mensaje de error:" + j.getMessage());
    }
  }
コード例 #22
0
  private void viewReport() throws Exception {
    Date fromDate = fromDatePicker.getDate();
    Date toDate = toDatePicker.getDate();

    if (fromDate.after(toDate)) {
      POSMessageDialog.showError(
          BackOfficeWindow.getInstance(),
          com.floreantpos.POSConstants.FROM_DATE_CANNOT_BE_GREATER_THAN_TO_DATE_);
      return;
    }

    fromDate = DateUtil.startOfDay(fromDate);
    toDate = DateUtil.endOfDay(toDate);

    ReportService reportService = new ReportService();
    MenuUsageReport report = reportService.getMenuUsageReport(fromDate, toDate);

    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("reportTitle", "========= LAPORAN PENJUALAN PER MENU ==========");
    map.put("fromDate", ReportService.formatShortDate(fromDate));
    map.put("toDate", ReportService.formatShortDate(toDate));
    map.put("reportTime", ReportService.formatFullDate(new Date()));

    JasperReport jasperReport =
        (JasperReport)
            JRLoader.loadObject(
                getClass().getResource("/com/floreantpos/ui/report/menu_usage_report.jasper"));
    JasperPrint jasperPrint =
        JasperFillManager.fillReport(
            jasperReport, map, new JRTableModelDataSource(report.getTableModel()));
    JRViewer viewer = new JRViewer(jasperPrint);
    reportContainer.removeAll();
    reportContainer.add(viewer);
    reportContainer.revalidate();
  }
コード例 #23
0
  public void abrirRelatorio(ActionEvent evt) {
    try {
      String arquivo =
          "condominio/core/administrativo/relatorios/Blank_A4.jasper"; // arquivo de relatorio
      java.io.InputStream file =
          getClass().getClassLoader().getResourceAsStream(arquivo); // carrego o arquivo
      List<TIPO_MORADOR> allTipoMorador = pCrud.getAllTipoMorador();
      JRBeanArrayDataSource dataSource =
          new JRBeanArrayDataSource(
              allTipoMorador.toArray(
                  new TIPO_MORADOR
                      [allTipoMorador
                          .size()])); // aqui eu crio um datasource usando a propria jtable
      Map parametros =
          new HashMap(); // apenas crio um map, mas nem passo parametro nem nada, os parametros sao
      // as colunas da jtable
      JasperPrint printer = JasperFillManager.fillReport(file, parametros, dataSource);

      JRViewer view = new JRViewer(printer);

      view.setVisible(true);

      SwingNode panel = new SwingNode();
      panel.prefHeight(500);
      panel.prefWidth(500);
      panel.setContent(view);

      relat.getChildren().add(panel);

    } catch (JRException e) {
      e.printStackTrace();
    }
  }
コード例 #24
0
  private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

    try {

      JOptionPane.showMessageDialog(rootPane, "Creando Pdf ");

      InputStream marca_agua;
      marca_agua = new FileInputStream("plantilla-para-programa02.jpg");
      int añoi = fechai.getCalendar().get(Calendar.YEAR);
      int mesi = fechai.getCalendar().get(Calendar.MONTH) + 1;
      int diai = fechai.getCalendar().get(Calendar.DAY_OF_MONTH);

      fi = añoi + "-" + mesi + "-" + diai;

      int añof = fechaf.getCalendar().get(Calendar.YEAR);
      int mesf = fechaf.getCalendar().get(Calendar.MONTH) + 1;
      int diaf = fechaf.getCalendar().get(Calendar.DAY_OF_MONTH);

      ff = añof + "-" + mesf + "-" + diaf;
      System.out.println(fi);
      System.out.println(ff);
      System.out.println(idc);

      n.conectar();

      Map parameters = new HashMap();

      parameters.put("fechai", fi);
      parameters.put("fechaf", ff);
      parameters.put("cliente", idc);
      parameters.put("marca", marca_agua);

      JasperReport report = JasperCompileManager.compileReport("estado_cuenta.jrxml");
      JasperPrint print = JasperFillManager.fillReport(report, parameters, n.coneccion);
      // Exporta el informe a PDF
      JasperExportManager.exportReportToPdfFile(print, "estado_cuenta.pdf");

      JOptionPane.showMessageDialog(rootPane, "Pdf creado correctamente enviando mail ");

      if (email.getText().length() == 0) {

        JOptionPane.showMessageDialog(rootPane, "Ingrese Un correo para poder enviar mail ");

      } else {

        JOptionPane.showMessageDialog(rootPane, "Enviando mail ");
        enviar();
      }

      // Para visualizar el pdf directamente desde java
      // JasperViewer.viewReport(print, false);

    } catch (ClassNotFoundException ex) {
      Logger.getLogger(estados_cuenta.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JRException ex) {
      Logger.getLogger(estados_cuenta.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
      Logger.getLogger(estados_cuenta.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
コード例 #25
0
  public JasperPrint gerarRelatorio(String nomeRelatorio, Collection<TbItem> CollectionTbItem) {

    JasperPrint jasperPrint = null;

    try {
      jasperPrint =
          JasperFillManager.fillReport(
              pathToReportPackage.replace("%20", " ") + nomeRelatorio,
              new HashMap<String, Object>(),
              new JRBeanCollectionDataSource(CollectionTbItem));

    } catch (JRException e) {
      JOptionPane.showMessageDialog(
          null,
          "Ocorreu um erro ao gerar o relatório.\n" + e.getMessage(),
          "Erro ao gerar o relatório",
          JOptionPane.ERROR_MESSAGE);
    } catch (Exception e) {
      JOptionPane.showMessageDialog(
          null,
          "Ocorreu um erro geral ao gerar o relatório.\n" + e.getMessage(),
          "Erro ao gerar o relatório",
          JOptionPane.ERROR_MESSAGE);
    }

    return jasperPrint;
  }
コード例 #26
0
ファイル: Pre.java プロジェクト: JorgeBe93/Proyect-II
 private void btn_generarActionPerformed(
     java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btn_generarActionPerformed
   // TODO add your handling code here:
   this.dispose();
   try {
     Class.forName("com.mysql.jdbc.Driver");
     Connection con =
         (Connection)
             DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel db", "root", "user");
     HashMap par = new HashMap(); // no definimos ningún parámetro por eso lo dejamos así
     Map parametros = new HashMap();
     par.put("Cliente", tf_cliente.getText());
     par.put("Telefono", tf_telefono.getText());
     par.put("Dias", Integer.parseInt(tf_dias.getText()));
     par.put("Personas", Integer.parseInt(tf_personas.getText()));
     JasperPrint jp =
         JasperFillManager.fillReport(
             "C:/Proyecto-II/src/reportes/presupuestoHabit.jasper",
             par,
             con); // el primer parámetro es el camino del archivo, se cambia esta dirección por la
                   // dirección del archivo .jasper
     JasperViewer jv = new JasperViewer(jp, false);
     jv.setVisible(true);
     jv.setTitle("Presupuesto de Habitaciones y P/S");
     Image icon = new ImageIcon(getClass().getResource("/imagenes/hotel2.png")).getImage();
     jv.setIconImage(icon);
     jv.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
   } catch (Exception e) {
     e.printStackTrace();
   }
 } // GEN-LAST:event_btn_generarActionPerformed
コード例 #27
0
  private void btnTodosActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnTodosActionPerformed
    try {
      // Arquivo do Relatorio
      // String relatorio = "/META-INF/relatorio/relatorioEstoque.jasper";
      InputStream relatorio =
          this.getClass()
              .getClassLoader()
              .getResourceAsStream("META-INF/relatorio/relatorioCompras.jasper");
      // Lista a ser exibida no relatorio
      CompraDAO compraDao = new CompraDAO();
      List<Compra> compras = new LinkedList<>();

      for (Compra c : compraDao.ListarTodos()) {
        c.setNomeFornecedor(c.getProduto().getFornecedor().getNome());
        compras.add(c);
      }

      // Fonte de dados
      JRBeanCollectionDataSource fonteDados = new JRBeanCollectionDataSource(compras);

      // Gera o Relatorio
      JasperPrint relatorioGerado = JasperFillManager.fillReport(relatorio, null, fonteDados);

      // Exibe o Relatorio
      JasperViewer jasperViewer = new JasperViewer(relatorioGerado, false);
      this.dispose();
      jasperViewer.setVisible(true);

    } catch (JRException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(this, e.getMessage());
    }
  } // GEN-LAST:event_btnTodosActionPerformed
コード例 #28
0
  public void imprimir(List<Produto> produtos) throws IOException {

    try {
      // Projeto do Relatorio feito no iReport ou outro programa
      // OBS: Para evitar erros, colocar o projeto do Relatorio no mesmo diretorio desta classe, ou
      // seja, ambos devem estar juntos.

      InputStream is = getClass().getResourceAsStream("RelVenda.jrxml");
      System.out.println(is);

      JasperReport report = JasperCompileManager.compileReport(is);

      // passar a lista recebida no método

      JasperPrint print =
          JasperFillManager.fillReport(
              report, null, new JRBeanCollectionDataSource(produtos, false));

      // Diretorio que deseja salvar o relatorio

      JasperExportManager.exportReportToPdfFile(print, "c:/RelatorioVendas.pdf");

      // Para abrir o relatorio na pasta que vc salvou, utilizar o comando abaixo

      Runtime.getRuntime().exec("cmd /c start C:/RelatorioVendas.pdf");

    } catch (JRException e) {
      e.printStackTrace();
    }
  }
コード例 #29
0
 /**
  * @param reporte
  * @param parametros
  * @param conexionBD
  * @return
  * @throws JRException
  * @throws SQLException
  * @throws FileNotFoundException
  */
 public JasperPrint creaReporte(
     String reporte, Map<String, Object> parametros, Connection conexionBD)
     throws JRException, SQLException, FileNotFoundException {
   JasperPrint impresionJasper =
       JasperFillManager.fillReport(new FileInputStream(reporte), parametros, conexionBD);
   return impresionJasper;
 }
コード例 #30
0
  public byte[] getBytes(
      String valor,
      String fechaIni,
      String fechaFin,
      String dependen,
      String funcionario,
      String IdEstudia)
      throws JRException, SQLException {
    String bd = "Sigepex";
    String login = "******";
    String password = "******";
    String url = "jdbc:mysql://localhost/" + bd;
    Connection con = null;
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      con = (Connection) DriverManager.getConnection(url, login, password);
      if (!con.isClosed()) {
        System.out.println("Successfully connected to " + "MySQL server using TCP/IP...");
      }
    } catch (Exception e) {
      System.err.println("Exception: " + e.getMessage());
    }

    HashMap jasperParameter = new HashMap();
    jasperParameter.put("FECHAINICIO", fechaIni);
    jasperParameter.put("FECHAFIN", fechaFin);
    jasperParameter.put("DEPENDENCIA", dependen);
    jasperParameter.put("FUNCIONARIO", funcionario);
    jasperParameter.put("IDESTUDIANTE", IdEstudia);
    JasperReport report = null;
    try {
      report = JasperCompileManager.compileReport(valor);
    } catch (Exception t) {
      String h = "";
    }

    JasperPrint print = null;
    try {
      print = JasperFillManager.fillReport(report, jasperParameter, con);
    } catch (Exception eeee) {
      String ee = "";
    }

    // Exporta el informe a PDF
    String destFileNamePdf = "C:\\reporte1.pdf";
    // Creación del PDF
    JasperExportManager.exportReportToPdfFile(print, destFileNamePdf);

    byte[] pdfByteArray = JasperExportManager.exportReportToPdf(print);

    try {
      if (con != null) {
        con.close();
      }
    } catch (SQLException e) {
    }

    return pdfByteArray;
  }