No front-end estou utilizando react, meu controller está dessa forma
@Controller
public class RelatorioController {
@Autowired
private DataSource dbsource;
@RequestMapping(value = "gerarRelatorio", method = org.springframework.web.bind.annotation.RequestMethod.POST, produces = MediaType.APPLICATION_PDF_VALUE)
public @ResponseBody ResponseEntity<InputStreamResource> gerarRelatorio(@RequestBody String json) {
Relatorio relatorio;
try {
relatorio = new Relatorio(new JSONObject(json));
ByteArrayInputStream stream = relatorio.toByteArrayInputStream(dbsource);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "inline; filename=" + relatorio.getNome());
return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_PDF)
.body(new InputStreamResource(stream));
} catch (JSONException | IOException | JRException | SQLException e) {
return null;
}
}
}
e o metódo da classe Relatorio toByteArrayInputStream(dbsource) faz o seguinte:
public ByteArrayInputStream toByteArrayInputStream(DataSource dataSource)
throws JRException, SQLException, IOException {
compileJrxml();
Map<String, Object> params = new HashMap<String, Object>();
JasperPrint jasperPrinted = JasperFillManager.fillReport(
RelatorioKeys.JASPER_FILE_PATH + RelatorioKeys.JASPER_FILE_NAME, params, dataSource.getConnection());
JRPdfExporter exporter = new JRPdfExporter();
ByteArrayOutputStream byteArrayOuputStream = new ByteArrayOutputStream();
File pdf = new File(RelatorioKeys.JASPER_FILE_PATH + nome);
exporter.setExporterInput(new SimpleExporterInput(jasperPrinted));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(pdf));
exporter.exportReport();
byte[] byteArray = IOUtils.toByteArray(new FileInputStream(pdf));
byteArrayOuputStream.write(byteArray);
return new ByteArrayInputStream(byteArrayOuputStream.toByteArray());
}
No front-end com react recebo assim:
requestHandler.post('/gerarRelatorio', {})
.then(data => {
download(data, 'relatorio.pdf', 'application/pdf');
})
.catch(err => {
swal(
'Erro ao fazer requisição',
`Erro: ${err}`,
'error'
);
});
Sendo este RequestHandler uma classe que fiz para encapsular os detalhes gerais das request, como o banco, a porta e cross-origin,
Obrigado, Pedro