lunes, 1 de febrero de 2016

Mostrar pdf en iframe usando angularjs recibido de un api rest usando spring (@RestController ) + jasper report

Exportar reporte a pdf stream

byte[] response = null;
JasperPrint jasperPrint = reporteRepositorio.generarReporte(reportName,parameters);

if (TipoFormatoExportacion.STREAM.getValue().equals(formatType)) {

ByteArrayOutputStream baos = new ByteArrayOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, baos);
response=baos.toByteArray(); 

}

return response;

Controlador rest

@RequestMapping(method = RequestMethod.GET)
public void generarReporte(HttpServletRequest request,HttpServletResponse response) {

Map<String, Object> parameters = new HashMap<String, Object>();
try {
byte[] contents = reporteServicio.generarReporte("reportName",
TipoFormatoExportacion.STREAM.getValue(), parameters);
OutputStream os = response.getOutputStream();
response.setHeader("Content-Disposition", "inline; filename=file.pdf");
   response.setContentType("application/pdf");
response.setStatus(HttpServletResponse.SC_OK); 
response.setHeader("Cache-Control","private, must-revalidate, post-check=0, pre-check=0, max-age=1");
response.setHeader("Pragma","public");
os.write(contents);
os.close();
} catch (JRException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Fragmento html
<iframe id="visualizador"></iframe>
Controlador angularjs
$http.get(CONFIG.API_URL + "/" + namereport + "/" + params, { responseType: 'arraybuffer' })
    .success(function (data) {
        if (data) {
          var file = new Blob([data], {type: 'application/pdf'});
          var url = URL.createObjectURL(file);
        }
     document.getElementById('visualizador').setAttribute('src',url);   
}).error(function (error) {});