3

Necesito saber cómo puedo generar un reporte ireport en una variable StreamedContent. El reporte se encuentra en un paquete en el proyecto. La dificultad que tengo es que no puedo obtener la ruta del proyecto. Por el momento tengo esta porcion de codigo:

 public void generarReporte() {
    try{
        JRBeanCollectionDataSource solicitudLista = new JRBeanCollectionDataSource(super.getSolicitudes());
        byte[] pdf;            
        String report = FacesContext.getCurrentInstance().getExternalContext()
                        .getRealPath("/com/../reportes/solicitudAspirante.jasper");
        //InputStream report =   this.getClass().getClassLoader().getResourceAsStream("");
        //JasperReport report = JasperCompileManager.compileReport(reporte);
        JasperPrint print = JasperFillManager.fillReport(report, new HashMap(),solicitudLista);
        pdf = JasperExportManager.exportReportToPdf(print);
        this.archivo.setFile(new DefaultStreamedContent(new ByteArrayInputStream(pdf), "application/pdf"));  
    }catch(Exception e){
        System.out.println(e.getMessage());
    }

Se supone que en la variable report debería de cargar el reporte compilado pero no se encuentra en la ruta especificada. ¿Como puedo hacer para cargar el reporte?

2
  • 1
    OP deberías agregar tu código por medio de la herramienta, no por medio de una imagen el 30 nov. 2016 a las 14:19
  • 1
    Ya modifique la pregunta. Muchas gracias por el consejo. el 30 nov. 2016 a las 14:39

2 respuestas 2

2

Yo utilizo este código para generar el reporte en un pe:documentViewer:

Genera un documento:

public DefaultStreamedContent getImprimeOrdenInicioStream() {
    if (ordenInicioSelected != null) {
        String reportePath = "/archivos/ordenInicio/rptOrdenInicio.jasper";
        Map<String, Object> parametros = new HashMap<>();
        parametros.put("idOrdenInicio", ordenInicioSelected.getIdOrdenInicio());
        parametros.put("idPersona", usuario.getIdPersona().getIdPersona());

        return imprimePDFEnDocumentViewer(reportePath, parametros, "rptOrdenInicio");
    }
    return new DefaultStreamedContent();
}

En este método defino los parámetros del JasperReports.

Y luego llamo al otro método que se llama imprimeDPFEnDocumentViewer:

public DefaultStreamedContent imprimePDFEnDocumentViewer(String rutaReporte, Map parametros, String nombreReporte) {
    JasperPrint jasperPrint;

    try {
        // Obteniendo las rutas relativas de los archivos necesarios
        String reportePath = sc.getRealPath(rutaReporte);
        String logoPath = sc.getRealPath("/resources/images/logo.png");
        String escudoPath = sc.getRealPath("/resources/images/escudo.png");
        parametros.put("logo_isbm", logoPath);
        parametros.put("escudo_logo", escudoPath);
        parametros.put(JRParameter.REPORT_LOCALE, locale);

        // Obteniendo la conexion del JDNI
        Context initialContext = new InitialContext();
        if (initialContext == null) {
            System.out.println("Problema con el JNDI. No se puede obtener el InitialContext.");
        }
        DataSource datasource = (DataSource) initialContext.lookup(DATASOURCE_CONTEXT);
        if (datasource != null) {
            conn = datasource.getConnection();
        } else {
            System.out.println("Error al buscar el datasource.");
        }

        jasperPrint = JasperFillManager.fillReport(reportePath, parametros, conn);

        // Mostrando el documento
        byte[] docPdf = JasperExportManager.exportReportToPdf(jasperPrint);
        return new DefaultStreamedContent(new ByteArrayInputStream(docPdf), "application/pdf", nombreReporte);

    } catch (JRException | NamingException ex) {
        Logger.getLogger(GeneraReportes.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (SQLException ex) {
        System.out.println("No se puede obtener la conexion: " + ex);
        return null;
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(GeneraReportes.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            }
        }
    }
}

Todas las rutas son relativas.

Luego en el xhtml lo llamo de la siguiente manera:

En un botón de un

<p:commandButton icon="ui-icon-print" title="#{msg.imprimir}" process="@this" oncomplete="PF('wDia').show()" update=":dia" rendered="true">
        <f:setPropertyActionListener value="#{inicio}" target="#{generaReportes.ordenInicioSelected}" />
</p:commandButton>

La variable #{inicio} es el atributo var del dataTable y #{generaReportes.ordenInicioSelected} es una variable en bean que lo genera, que se utiliza en el código que puse arriba.

2
0

Escribo la clase creada, para que otras personas puedan utilizarla.

public class GenerarReporte {

private Map<String, Object> parameters;
private String reportPath;

public GenerarReporte(Map<String, Object> parameters, String reportPath) {
    this.reportPath = reportPath;
    this.parameters = parameters;
}

public DefaultStreamedContent generarReporte() {
    DefaultStreamedContent file = new DefaultStreamedContent();
    if (this.parameters != null && this.reportPath != null) {
        file = imprimePDFEnDocumentViewer(this.reportPath, this.parameters, "reporte");
    }
    return file;
}

private DefaultStreamedContent imprimePDFEnDocumentViewer(String rutaReporte, Map parameters, String nombreReporte) {
    JasperPrint jasperPrint;
    DefaultStreamedContent content = new DefaultStreamedContent();
    byte[] docPdf;
    try {
        // Obteniendo las rutas relativas de los archivos necesarios
        ExternalContext sc = FacesContext.getCurrentInstance().getExternalContext();
        String reportePath = sc.getRealPath(rutaReporte);
        //JRBeanCollectionDataSource datasourcesFields = new JRBeanCollectionDataSource(fields);           
        jasperPrint = JasperFillManager.fillReport(reportePath, parameters, new JREmptyDataSource());
        // Mostrando el documento
        docPdf = JasperExportManager.exportReportToPdf(jasperPrint);
        content = new DefaultStreamedContent(new ByteArrayInputStream(docPdf), "application/pdf", nombreReporte);

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return content;
}

}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.