Exemplo n.º 1
0
 /** 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;
   }
 }
  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());
    }
  }
Exemplo n.º 3
0
  /**
   * 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;
    }
  }
Exemplo n.º 4
0
  @SuppressWarnings("unchecked")
  public static void main(String[] args) {
    try {
      URL url =
          JasperAB.class
              .getClassLoader()
              .getResource("br/com/analiseFornecedores/relatorio/relatorio_controle_1.jasper");
      File reportFile = new File(url.getFile());
      JasperReport relatorio = (JasperReport) JRLoader.loadObject(reportFile.getPath());
      Collection<RelatorioControleVO> lista = new ArrayList<RelatorioControleVO>();

      AnaliseRN rn = new AnaliseRN();
      Collection<AnaliseVO> analises = new ArrayList<AnaliseVO>();
      try {
        AnaliseVO filtro = new AnaliseVO();
        analises = rn.obterPorFiltro(filtro);
        lista = rn.obterRelatorioControle(analises);
      } catch (ExecaoRegraNegocio e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }

      JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(lista);
      Map<?, ?> param = new HashMap();
      JasperPrint jasperPrint = JRFiller.fillReport(relatorio, param, ds);
      JasperViewer.viewReport(jasperPrint, true);
    } catch (JRException e) {
      e.printStackTrace();
    }
  }
  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();
    }
  }
Exemplo n.º 6
0
 public void print(boolean withPrintDialog) {
   try {
     JasperPrintManager.printReport(makeReport(), withPrintDialog);
   } catch (JRException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 7
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();
    }
  }
Exemplo n.º 8
0
 public byte[] gerarRelatorioHtml(
     List<Object> clAttrsRelatorio,
     String pathSistema,
     String pathReports,
     String pathImages,
     String nomeRelatorio)
     throws JRException {
   logger.entering(new Object[0]);
   Map<String, String> parametros = new HashMap<String, String>();
   parametros.put(CAMINHO_RELATORIOS, pathReports);
   parametros.put(CAMINHO_IMAGENS, pathImages);
   try {
     JasperRunManager.runReportToHtmlFile(
         pathReports + nomeRelatorio,
         pathSistema + "relatorio.html",
         parametros,
         new JRBeanCollectionDataSource(clAttrsRelatorio));
     logger.exiting(new Object[0]);
     return FileUtil.createByteArray(pathSistema + "relatorio.html");
   } catch (JRException e) {
     logger.exception(e.getMessage(), e);
     throw e;
   } catch (IOException e) {
     logger.exception(e.getMessage(), e);
     throw new JRException(e.getMessage(), e);
   }
 }
  private ByteArrayOutputStream concatenateDocs(
      byte[] originalDoc, Person person, StudentCandidacy candidacy)
      throws IOException, DocumentException {
    ByteArrayOutputStream concatenatedPdf = new ByteArrayOutputStream();
    PdfCopyFields copy = new PdfCopyFields(concatenatedPdf);

    try {
      copy.addDocument(new PdfReader(createAcademicAdminProcessSheet(person).toByteArray()));
    } catch (JRException e) {
      logger.error(e.getMessage(), e);
    }
    copy.addDocument(new PdfReader(originalDoc));
    copy.addDocument(new PdfReader(new SantanderPdfFiller().getFilledPdf(person).toByteArray()));
    copy.addDocument(
        new PdfReader(new SantanderCardPdfFiller().getFilledPdf(person, candidacy).toByteArray()));
    copy.addDocument(
        new PdfReader(new BPIPersonalInformationPdfFiller().getFilledPdf(person).toByteArray()));
    copy.addDocument(new PdfReader(new BPICardAEISTPdfFiller().getFilledPdf(person).toByteArray()));
    copy.addDocument(
        new PdfReader(new BPIDigitalDocumentionPdfFiller().getFilledPdf(person).toByteArray()));
    copy.addDocument(
        new PdfReader(new BPIProductsAndServicesPdfFiller().getFilledPdf(person).toByteArray()));
    copy.close();

    return concatenatedPdf;
  }
  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
 public static void main(String[] args) {
   try {
     compile("jasper_report_template.jrxml");
   } catch (JRException e) {
     e.printStackTrace();
   }
 }
  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;
  }
Exemplo n.º 13
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();
    }
  }
Exemplo n.º 14
0
  public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
      throws PrinterException {
    if (Thread.interrupted()) {
      throw new PrinterException("Current thread interrupted.");
    }

    pageIndex += pageOffset;

    if (pageIndex < 0 || pageIndex >= jasperPrint.getPages().size()) {
      return Printable.NO_SUCH_PAGE;
    }

    try {
      JRGraphics2DExporter exporter = new JRGraphics2DExporter();
      exporter.setParameter(JRExporterParameter.JASPER_PRINT, this.jasperPrint);
      exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, graphics);
      exporter.setParameter(JRExporterParameter.PAGE_INDEX, new Integer(pageIndex));
      exporter.exportReport();
    } catch (JRException e) {
      if (log.isDebugEnabled()) log.debug("Print failed.", e);

      throw new PrinterException(e.getMessage());
    }

    return Printable.PAGE_EXISTS;
  }
  public void executeReport() throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();

    HttpServletResponse response =
        (HttpServletResponse) facesContext.getExternalContext().getResponse();

    InputStream reportStream =
        facesContext.getExternalContext().getResourceAsStream("caminho_arquivo.jasper");

    response.setContentType("application/pdf");

    response.setHeader("Content-disposition", "inline;filename=relatorio.pdf");

    try {
      ServletOutputStream servletOutputStream = response.getOutputStream();

      JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(arrayList);

      JasperRunManager.runReportToPdfStream(
          reportStream, servletOutputStream, parameters, datasource);

      servletOutputStream.flush();
      servletOutputStream.close();
    } catch (JRException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      facesContext.responseComplete();
    }
  }
Exemplo n.º 16
0
  /**
   * 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;
    }
  }
Exemplo n.º 17
0
 protected void onGenerarInformeButtonActionPerformed(ActionEvent e) {
   // crear informe pasandole los datos en el constructor
   try {
     new Informe(this);
   } catch (JRException e1) {
     e1.printStackTrace();
   }
 }
Exemplo n.º 18
0
 private void close() {
   JRTableModelDataSource ds = new JRTableModelDataSource(m_model);
   try {
     m_jasperPrint = JasperFillManager.fillReport(m_jasperReport, m_parameters, ds);
   } catch (JRException e) {
     e.printStackTrace();
   }
   m_jrv = new JRViewer(m_jasperPrint);
 }
 @Override
 public void execute() {
   super.execute();
   try {
     if (var != null) jDataset.addVariable((JRDesignVariable) var);
   } catch (JRException e) {
     e.printStackTrace();
   }
 }
  @SuppressWarnings({"rawtypes", "unchecked"})
  protected void procesar(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    /*CABECERA DE SALIDA*/
    response.setHeader("Content-Disposition", "attachment; filename=\"CronogramaCredito.pdf\";");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("application/pdf");

    /*OBTIENE FLUJO DE SALIDA*/
    ServletOutputStream outputStream = response.getOutputStream();

    /*PARAMETROS*/
    Parameters parameters = Parameters.getInstance();

    /*SERVICIO DE GENERACION DE REPORTES*/
    ReporteJasperServiceImpl jasperServiceImpl = new ReporteJasperServiceImpl();

    /*RECUPERA DATOS DE LA SIMULACION EN SESION*/
    HttpSession session = request.getSession(true);
    CreditoCabeceraBO creditoCabeceraBO =
        (CreditoCabeceraBO) session.getAttribute("creditoCabeceraBO");
    CreditoCronogramaBO creditoCronogramaBO =
        (CreditoCronogramaBO) session.getAttribute("creditoCronogramaBO");
    List<Cuota> listaCuotasCredito = (List<Cuota>) session.getAttribute("listaCuotasCredito");

    try {
      /* CARGA PARAMETROS PARA REPORTE JASPER*/
      JasperReport reporte =
          (JasperReport)
              JRLoader.loadObject(
                  this.getClass()
                      .getClassLoader()
                      .getResourceAsStream(parameters.getKey("REPORTE_CREDITO_PYME")));

      /* CARGA PARAMETROS DEL REPORTE*/
      Map paramReporte =
          jasperServiceImpl.getParamReporCredPYME(creditoCabeceraBO, creditoCronogramaBO);

      /* GENERA REPORTE*/
      JRExporter exporterPDF =
          jasperServiceImpl.getExporterJasper(
              reporte, paramReporte, new JRBeanCollectionDataSource(listaCuotasCredito));
      exporterPDF.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);

      /*MUESTRA REPORTE EN LINEA*/
      exporterPDF.exportReport();

    } catch (JRException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 public static void compile(final String sourceFileName) throws JRException {
   System.out.println("Compiling Report Design ...");
   try {
     JasperCompileManager.compileReportToFile(sourceFileName);
   } catch (JRException e) {
     e.printStackTrace();
     throw e;
   }
   System.out.println("Done compiling!!! ...");
 }
 private void testImage(String name, int index) {
   BatikRenderer batikRenderer =
       ((BatikRenderer) ((JRPrintImage) getElementAt(name, index)).getRenderable());
   try {
     byte[] data = batikRenderer.getImageData(DefaultJasperReportsContext.getInstance());
     Assert.assertNotNull(data);
   } catch (JRException e) {
     Assert.fail(e.getMessage());
   }
 }
  /**
   * Este método se encarga de generar el reporte
   *
   * @param params diccionario de datos
   */
  public void generarReporte(Map params) {
    try {
      nConexion = new NegocioConexion();
      reporte = (JasperReport) JRLoader.loadObjectFromFile(ruta);
      reporteFill = JasperFillManager.fillReport(reporte, params, nConexion.conexion());

      visualizarReporteGenerado();
    } catch (JRException ex) {
      System.err.println(ex.getMessage());
    }
  }
Exemplo n.º 24
0
  private JRRenderable getRenderer() {
    JRRenderable imageRenderer = null;
    Image awtImage = null;

    try {
      awtImage = JRImageLoader.getImage(JRImageLoader.SUBREPORT_IMAGE);
      imageRenderer = JRImageRenderer.getInstance(awtImage, JRImage.ON_ERROR_TYPE_ERROR);
    } catch (JRException e) {
      e.printStackTrace(); // FIXMECONVERT use logging
    }

    return imageRenderer;
  }
Exemplo n.º 25
0
 public void viewJasper(String path, String name, String outPath, List<?> list) {
   name = parseJrXml(path, name);
   HashMap<String, Object> hm = new HashMap<String, Object>();
   JasperPrint print;
   try {
     print =
         JasperFillManager.fillReport(outPath + name, hm, new JRBeanCollectionDataSource(list));
     JasperViewer jrview = new JasperViewer(print, false);
     jrview.setPreferredSize(new Dimension(200, 100));
     jrview.setVisible(true);
   } catch (JRException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 26
0
 public String exporterPDF() {
   if (codeevaluation != 0) {
     try {
       this.service.imprimerNotesClasse(codeevaluation);
     } catch (IOException e) {
       Repertoire.addMessageerreur("Une erreur est survenue lors de l'impresson", e);
       e.printStackTrace();
     } catch (JRException e) {
       Repertoire.addMessageerreur("Une erreur est survenue lors de l'impresson", e);
       e.printStackTrace();
     }
   }
   return null;
 }
Exemplo n.º 27
0
 private String parseJrXml(String path, String name) {
   // 如果是.jrxml手工编译
   if (name.contains(".jrxml")) {
     try {
       // 在当前目录编译
       JasperCompileManager.compileReportToFile(path + name);
       name = name.replace(".jrxml", ".jasper");
     } catch (JRException e1) {
       e1.printStackTrace();
     }
   }
   System.out.println(name);
   return name;
 }
  private void btnFornecedorActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnFornecedorActionPerformed

    try {
      // Pegando o id do Produto

      String fornecedor = JOptionPane.showInputDialog("Insira o Id do Fornecedor");

      // 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 comprasDAO = new CompraDAO();

      List<Compra> compras = comprasDAO.ListarTodos();
      List<Compra> comprasFiltro = new LinkedList<>();
      for (Compra c : compras) {
        if (c.getProduto().getFornecedor().getId() == Long.parseLong(fornecedor)) {
          comprasFiltro.add(c);
        }
      }

      if (!comprasFiltro.isEmpty()) {

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

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

        // Exibe o Relatorio
        JasperViewer jasperViewer = new JasperViewer(relatorioGerado, false);
        this.dispose();
        jasperViewer.setVisible(true);
      } else {
        JOptionPane.showMessageDialog(rootPane, "Fornecedor não encontrado !");
      }

    } catch (JRException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(this, e.getMessage());
    } catch (NumberFormatException e) {
      JOptionPane.showMessageDialog(rootPane, "Id inválido !");
    }
  } // GEN-LAST:event_btnFornecedorActionPerformed
Exemplo n.º 29
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
Exemplo n.º 30
0
  /** Generates and displays <b>BR Report</b>. */
  public static JasperPrint getBrReport() {
    HashMap inputParameters = new HashMap();
    inputParameters.put("REPORT_LOCALE", Locale.getDefault());
    inputParameters.put("today", new Date());
    inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
    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);
      if (beans[i].getFeedback() != null) {
        String feedback = beans[i].getFeedback();
        feedback = feedback.substring(0, feedback.indexOf("::::"));
        beans[i].setFeedback(feedback);
      }

      if (i > 0) {
        String idPrev = beans[i - 1].getId();
        String technicalTypeCodePrev = beans[i - 1].getTechnicalTypeCode();
        String id = beans[i].getId();
        String technicalTypeCode = beans[i].getTechnicalTypeCode();

        if (id.equals(idPrev) && technicalTypeCode.equals(technicalTypeCodePrev)) {

          beans[i].setId("");
          beans[i].setBody("");
          beans[i].setDescription("");
          beans[i].setFeedback("");
          beans[i].setTechnicalTypeCode("");
        }
      }
    }

    JRDataSource jds = new JRBeanArrayDataSource(beans);
    try {
      return JasperFillManager.fillReport(
          ReportManager.class.getResourceAsStream("/reports/BrReport.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;
    }
  }