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();
    }
  }
Beispiel #2
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);
   }
 }
Beispiel #3
0
  public static void execute(
      ServletContext sc, HttpServletRequest request, HttpServletResponse response) {
    try {
      List<RelatorioUsuario> listRelusers = new ArrayList<RelatorioUsuario>();

      listUsers = UsuariosRelDAO.getAll();

      for (int i = 0; i < listUsers.size(); i++) {
        RelatorioUsuario relUsers = new RelatorioUsuario();
        relUsers.setId(listUsers.get(i).getid());
        relUsers.setLogin(listUsers.get(i).getLogin());
        relUsers.setNome(listUsers.get(i).getNome());
        relUsers.setTipoUsuario(listUsers.get(i).getTipoUsuario());
        listRelusers.add(relUsers);
      }

      JRDataSource jrds = new JRBeanCollectionDataSource(listRelusers);

      // parametros do relatorio
      HashMap parameters = new HashMap();
      // lendo arquivo jasper
      File reportFile = new File(sc.getRealPath("/WEB-INF/rel/rel_cpi.jasper"));
      // String fileName = "teste";
      byte[] bytes = null;
      try {
        bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), parameters, jrds);
        // JasperPrint print = JasperFillManager.fillReport(reportFile.getPath(), parameters, jrds);

        // bytes = JasperExportManager.exportReportToPdf(print);
        // JasperViewer.viewReport( reportFile.getName() + ".pdf", false );
      } catch (Exception e) {
        e.printStackTrace();
        return;
      }
      //
      if (bytes != null && bytes.length > 0) {
        response.setContentType("application/pdf");
        response.setContentLength(bytes.length);
        ServletOutputStream ouputStream = response.getOutputStream();
        ouputStream.write(bytes, 0, bytes.length);
        ouputStream.flush();
        ouputStream.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * 用jasperReport打印Pdf
   *
   * @param request
   * @param response/
   * @param reportFilePath jasper报表文件路径
   * @param paramMap 字段
   * @param dataList
   * @throws IOException
   * @throws JRException void
   * @author xiaobao @Create Mar 5, 2012 10:01:39 AM
   */
  public static String printReportToHTML(
      HttpServletRequest request,
      HttpServletResponse response,
      String reportFilePath,
      Map<String, Object> paramMap,
      List dataList)
      throws IOException, JRException {
    JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(dataList);
    String path = JasperRunManager.runReportToHtmlFile(reportFilePath, paramMap, dataSource);

    String fileName = paramMap.get("fileName").toString();
    try {
      fileName = new String(fileName.getBytes(), "iso8859-1");
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }
    return path;
  }
Beispiel #5
0
  public byte[] gerarRelatorio(
      List<Object> clAttrsRelatorio, 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 {
      JasperReport jasperReport = (JasperReport) JRLoader.loadObject(pathReports + nomeRelatorio);

      logger.exiting(new Object[0]);
      return JasperRunManager.runReportToPdf(
          jasperReport, parametros, new JRBeanCollectionDataSource(clAttrsRelatorio));
    } catch (JRException e) {
      logger.exception(e.getMessage(), e);
      throw e;
    }
  }
 /**
  * 用jasperReport导出Pdf
  *
  * @param request
  * @param response
  * @param reportFilePath jasper报表文件路径
  * @param paramMap 字段
  * @param dataList
  * @throws IOException
  * @throws JRException void
  * @author xiaobao @Create Mar 5, 2012 10:01:39 AM
  */
 public static String exportReportToPDF(
     HttpServletRequest request,
     HttpServletResponse response,
     String reportFilePath,
     Map<String, Object> paramMap,
     List dataList)
     throws IOException, JRException {
   JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(dataList);
   String fileName = paramMap.get("fileName").toString();
   fileName = fileName + ".pdf";
   String path =
       request.getRealPath("/")
           + File.separator
           + "report"
           + File.separator
           + "export"
           + File.separator
           + fileName;
   JasperRunManager.runReportToPdfFile(reportFilePath, path, paramMap, dataSource);
   return fileName;
 }
  public void run() throws JRException {
    long start = System.currentTimeMillis();
    // Preparing parameters
    Image image = Toolkit.getDefaultToolkit().createImage("dukesign.jpg");
    MediaTracker traker = new MediaTracker(new Panel());
    traker.addImage(image, 0);
    try {
      traker.waitForID(0);
    } catch (Exception e) {
      e.printStackTrace();
    }

    Map parameters = new HashMap();
    parameters.put("ReportTitle", "The First Jasper Report Ever");
    parameters.put("MaxOrderID", new Integer(10500));
    parameters.put("SummaryImage", image);

    JasperRunManager.runReportToPdfFile(
        "build/reports/FirstJasper.jasper", parameters, getDemoHsqldbConnection());
    System.err.println("PDF running time : " + (System.currentTimeMillis() - start));
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    ServletOutputStream servletOutputStream = response.getOutputStream();
    InputStream reportStream =
        getServlet()
            .getServletConfig()
            .getServletContext()
            .getResourceAsStream("/reportes/ReporteSTDExterno.jasper");
    response.setContentType("application/pdf");

    String ls_mensaje_exp = (String) request.getSession().getAttribute("numero_expediente");
    String mensaje_clave = (String) request.getSession().getAttribute("mensaje_clave");
    String usuario = (String) request.getSession().getAttribute("nombreusuario");
    HashMap<String, String> parameterMap = new HashMap<String, String>();
    parameterMap.put("numero_expediente", ls_mensaje_exp);
    parameterMap.put("mensaje_clave", mensaje_clave);
    parameterMap.put("usuario", usuario);

    // Class.forName("com.mysql.jdbc.Driver");

    //  connection =
    // DriverManager.getConnection("jdbc:mysql://localhost:3306/flightstats?user=root&password=password");

    JasperRunManager.runReportToPdfStream(
        reportStream, servletOutputStream, parameterMap, new JREmptyDataSource());

    // connection.close();

    servletOutputStream.flush();
    servletOutputStream.close();

    return null;
  }
  /**
   * 用jasperReport导出Pdf
   *
   * @param request
   * @param response/
   * @param reportFilePath jasper报表文件路径
   * @param paramMap 字段
   * @param dataList
   * @throws IOException
   * @throws JRException void
   * @author xiaobao @Create Mar 5, 2012 10:01:39 AM
   */
  public static void viewReportToPDF(
      HttpServletRequest request,
      HttpServletResponse response,
      String reportFilePath,
      Map<String, Object> paramMap,
      List dataList)
      throws IOException, JRException {
    JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(dataList);
    byte[] bytes = JasperRunManager.runReportToPdf(reportFilePath, paramMap, dataSource);

    String fileName = paramMap.get("fileName").toString();
    try {
      fileName = new String(fileName.getBytes(), "iso8859-1");
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }
    OutputStream out = response.getOutputStream();
    response.setContentType("application/pdf;charset=GBK");
    response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    out.write(bytes, 0, bytes.length);
    out.flush();
    out.close();
  }
Beispiel #10
0
  public ActionForward print(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws JRException, IOException, ServletException {
    MemberManager mm = (MemberManager) getBean(IConstants.MEMBER_MANAGER_BEAN_NAME);
    StudAffairManager sm = (StudAffairManager) getBean("studAffairManager");
    StudAffairDAO dao = (StudAffairDAO) getBean("studAffairDAO");
    HttpSession session = request.getSession(false);
    DynaActionForm aForm = (DynaActionForm) form;
    UserCredential user = (UserCredential) session.getAttribute("Credential");

    String qty = aForm.getString("qty").trim();
    boolean setupPrinter = false;
    boolean isPrint = false;

    ActionMessages messages = new ActionMessages();

    if (!qty.equals("")) {
      String idno = user.getMember().getIdno();
      String prefix = idno.substring(idno.length() - 5);
      int q = Integer.parseInt(qty);
      String[] codes = new String[q];
      String rano = prefix + this.getRandom(4);
      String hql = "From AssessPaper Where serviceNo='" + rano + "' And idno='" + idno + "'";

      // 建立服務編號
      boolean isUniq = false;
      for (int j = 0; j < q; j++) {
        while (true) {
          rano = prefix + this.getRandom(4);
          isUniq = true;
          if (dao.submitQuery(hql).isEmpty()) {
            // 檢查服務編號是否重複
            for (int k = 0; k < j; k++) {
              if (rano == codes[k]) {
                isUniq = false;
                break;
              }
            }
            if (isUniq) {
              codes[j] = rano;
              break;
            }
          }
        }
      }
      // Insert into DB
      ActionMessages msg = mm.addNewAssessPaper(idno, codes);
      if (!msg.isEmpty()) {
        messages.add(
            ActionMessages.GLOBAL_MESSAGE, new ActionMessage("MessageN1", "滿意度調查列印資料新增失敗:" + msg));
        saveErrors(request, messages);
        setContentPage(request, "personnel/AssessPaperPrint.jsp");
        return mapping.findForward(IConstants.ACTION_MAIN_NAME);
      }

      // TODO: print the paper in pdf format
      String reportSourceFile = "/WEB-INF/reports/AssessPaper.jrxml";
      String reportCompiledFile = "/WEB-INF/reports/AssessPaper.jasper";
      List<Object> printData = new ArrayList<Object>();
      ServletContext context = request.getSession().getServletContext();
      JasperReportUtils.initJasperReportsClasspath(request);

      printData = fillPrintData(codes);

      DecimalFormat df = new DecimalFormat(",##0.0");
      File reportFile = null;
      reportFile = new File(context.getRealPath(reportCompiledFile));
      // 需要時再編譯即可
      // if (!reportFile.exists()) {
      JasperReportUtils.compileJasperReports(context.getRealPath(reportSourceFile));
      reportFile = new File(context.getRealPath(reportCompiledFile));
      if (!reportFile.exists())
        throw new JRRuntimeException("查無\"AssessPaper.jasper\"檔案,請電洽電算中心,謝謝!!");
      // }

      Map<String, String> parameters = new HashMap<String, String>();

      JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportFile.getPath());

      parameters.put("idno", idno);
      parameters.put("userName", user.getMember().getName());
      parameters.put("PrintDate", Toolket.Date2Str(new Date())); // 列印日期

      String[] fields = {
        "serviceNo0",
        "serviceNo1",
        "serviceNo2",
        "serviceNo3",
        "serviceNo4",
        "serviceNo5",
        "serviceNo6",
        "serviceNo7",
        "serviceNo8",
        "serviceNo9"
      };

      JasperPrint jasperPrint =
          JasperFillManager.fillReport(
              jasperReport, parameters, new HibernateQueryResultDataSource(printData, fields));
      // jasperPrint.
      // 列印或預覽
      if (isPrint) {
        JasperPrintManager.printReport(jasperPrint, setupPrinter);
      } else {
        byte[] bytes =
            JasperRunManager.runReportToPdf(
                jasperReport, parameters, new HibernateQueryResultDataSource(printData, fields));

        Calendar td = Calendar.getInstance();
        String ran =
            ""
                + (td.get(Calendar.MINUTE))
                + (td.get(Calendar.SECOND))
                + (td.get(Calendar.MILLISECOND));
        String ranDir = "/WEB-INF/reports/temp/" + ran;

        File tempdir = new File(context.getRealPath(ranDir));
        if (!tempdir.exists()) tempdir.mkdirs();

        OutputStream os =
            new BufferedOutputStream(
                new FileOutputStream(new File(context.getRealPath(ranDir + "/AssessPaper.pdf"))));
        JasperExportManager.exportReportToPdfStream(jasperPrint, os);
        JasperReportUtils.printPdfToFrontEnd(response, bytes);
        os.close();
        Toolket.deleteDIR(tempdir);
        return null;
      }

    } else {
      messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("MessageN1", "請輸入欲列印張數!"));
      saveErrors(request, messages);
    }
    setContentPage(request, "personnel/AssessPaperPrint.jsp");
    return unspecified(mapping, form, request, response);
  }
  @SuppressWarnings("unchecked")
  public void gerarRelatorio() {

    FacesContext context = FacesContext.getCurrentInstance();

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

    try {

      String caminho =
          context.getExternalContext().getRealPath("/WEB-INF/relatorio/form_respondido.jasper");

      @SuppressWarnings("rawtypes")
      HashMap parametro = new HashMap();

      parametro.put("avaliado_id", this.idAvaliado);
      parametro.put("processo_id", this.idProcesso);
      parametro.put("media_final", this.media);
      parametro.put("conceito", this.descricaoConceito);

      byte[] bytes =
          JasperRunManager.runReportToPdf(caminho, parametro, ControlaConexao.getConexao());

      if (bytes.length != 0 && bytes != null) {
        ServletOutputStream saida = response.getOutputStream();

        response.setContentType("application/pdf");
        response.setContentLength(bytes.length);
        saida.write(bytes, 0, bytes.length);
        saida.flush();
        saida.close();

        context.responseComplete();
      } else {
        FacesContext.getCurrentInstance()
            .addMessage(
                null,
                new FacesMessage(
                    FacesMessage.SEVERITY_WARN,
                    "Não foi possível gerar relatório. ",
                    "Tente novamente mais tarde."));
      }

    } catch (IOException e) {
      System.out.println("IOException " + e.getMessage());
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              new FacesMessage(
                  FacesMessage.SEVERITY_WARN,
                  "Não foi possível gerar relatório. ",
                  "Tente novamente mais tarde."));

    } catch (JRException e) {
      System.out.println("JRE: " + e.getMessage());
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              new FacesMessage(
                  FacesMessage.SEVERITY_WARN,
                  "Não foi possível gerar relatório. ",
                  "Tente novamente mais tarde."));

    } catch (SQLException e) {
      System.out.println("JRE: " + e.getMessage());
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              new FacesMessage(
                  FacesMessage.SEVERITY_WARN,
                  "Não foi possível gerar relatório. ",
                  "Tente novamente mais tarde."));
    }

    media = 0;
    nota = 0;
    descricaoConceito = "";
  }