Olá pessoal,
estou gerando relatórios em PDF pelo Jasper Reports da seguinte forma:
ManagedBean:
public void rpt() {
... gera collections, hashmap, etc...
String reportPath=FacesContext.getCurrentInstance().getExternalContext().getRealPath(relatorio);
JRBeanCollectionDataSource jr=new JRBeanCollectionDataSource(colecao);
JasperPrint jasperPrint = JasperFillManager.fillReport(reportPath, parametros, jr);
HttpServletResponse httpResponse=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
httpResponse.setContentType("application/pdf");
httpResponse.addHeader("Content-disposition", "inline; filename=nome.pdf");
//httpResponse.addHeader("Content-disposition", "attachment; filename=nome.pdf");
ServletOutputStream servletOutputStream = httpResponse.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
FacesContext.getCurrentInstance().responseComplete();
}
Para visualização, estou criando uma janela popup da seguinte forma:
Teste.xhtml:
<p:commandButton value="Abrir relatório" actionListener="#{MB.rpt()}" ajax="false" onclick="window.open('#', 'Relatorio', 'STATUS=NO, TOOLBAR=NO, LOCATION=NO, DIRECTORIES=NO, RESISABLE=YES, SCROLLBARS=YES, width='+screen.width-20+',height='+screen.height-10,true);target='Relatorio'"/>
Funciona, mas a apresentação é muito ruim, pois eu não gostaria de ter que abrir este popup. Pensei em abrir o PDF direto num dialog do Primefaces.
Tente fazer da seguinte forma:
ManagedBean:
private StreamedContent sc;
public void geraPDF(){
pdfPronto=false;
String reportPath=FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/relatorios/relteste.jasper");
ByteArrayOutputStream os=new ByteArrayOutputStream();
try{
JRBeanCollectionDataSource jr=new JRBeanCollectionDataSource(dev);
JasperPrint jasperPrint = JasperFillManager.fillReport(reportPath, param, jr);
JasperExportManager.exportReportToPdfStream(jasperPrint, os);
os.close();
}catch(Exception e){e.printStackTrace();}
sc=new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()),"application/pdf","Relatorio.pdf");
pdfPronto=true;
}
public StreamedContent getPDF(){
return sc;
}
Teste.xhtml:
<h:form>
<p:commandButton value="Abrir relatório" action="#{MB.geraPDF()}" icon="ui-icon-person" update=":relatorio" oncomplete="dlg.show();"/>
</h:form>
<p:dialog widgetVar="dlg" id="relatorio">
<h:panelGroup rendered="#{MB.pdfPronto}">
#{MB.PDF.contentType}
<p:media id="pdf2" value="#{MB.PDF}" player="pdf" width="500px" height="500px" >Não foi possível abrir o arquivo PDF</p:media>
</h:panelGroup>
</p:dialog>
Acontece que o dialog abre, as informações ContentType e Name são mostradas confirmando a geração do pdf mas o p:media fica cinza...
Se eu deixar o ManagedBean no escopo de Sessão funciona, mas não acho que isso seja uma boa ideia, uma vez que a tendencia é a quantidade de ManagedBeans aumente bastante...
Alguém tem alguma ideia de como contornar esse problema?