I use this code to generate the report in a pe: documentViewer:
Generate a document:
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();
}
In this method I define the parameters of the JasperReports.
And then I call the other method called printDPFEnDocumentViewer:
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;
}
}
}
}
All routes are relative.
Then in the xhtml I call it in the following way:
On a button of a
<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>
The variable #{inicio}
is the attribute var
of the dataTable and #{generaReportes.ordenInicioSelected}
is a variable in bean that generates it, which is used in the code that I put above.