Não sei como retornar o relatório para o cliente ao invés de crialo em um diretório
@Controller
public class RelatorioController {
@Autowired
private HttpServletRequest request;
@Autowired
private TemporaryMachineIdDao tempMachineDao;
@RequestMapping(value = "/report/relatorio", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public String form(@RequestParam("id[]") int id[],
@RequestParam("dateIni") @DateTimeFormat(pattern = "dd/MM/yyyy") Date dateIni,
@RequestParam("dateFim") @DateTimeFormat(pattern = "dd/MM/yyyy") Date dateFim,
@RequestParam("horaInit") String horaInit, @RequestParam("minutoInit") String minutoInit,
@RequestParam("horaFim") String horaFim, @RequestParam("minutoFim") String minutoFim) throws JRException, SQLException, IOException {
Calendar cal = Calendar.getInstance();
Calendar calDateIni = Calendar.getInstance();
calDateIni.setTime(dateIni);
calDateIni.set(Calendar.HOUR_OF_DAY,Integer.valueOf(horaInit));
calDateIni.set(Calendar.MINUTE,Integer.valueOf(minutoInit));
Calendar calDateFim = Calendar.getInstance();
calDateFim.setTime(dateFim);
calDateFim.set(Calendar.HOUR_OF_DAY,Integer.valueOf(horaFim));
calDateFim.set(Calendar.MINUTE,Integer.valueOf(minutoFim));
Relatorio relatorio = new Relatorio();
relatorio.setTag((int) cal.getTimeInMillis());
relatorio.setMachinesIds(id);
relatorio.setDateIni(calDateIni.getTime());
relatorio.setDateFim(calDateFim.getTime());
System.out.println(relatorio.toString());
for (int i = 0; i < relatorio.getMachinesIds().length; i++) {
TemporaryMachineId tempMachine = new TemporaryMachineId();
tempMachine.setMachineId(relatorio.getMachinesIds()[i]);
tempMachine.setTag(relatorio.getTag());
tempMachineDao.gravar(tempMachine);
}
//String nome = request.getServletContext().getRealPath("/WEB-INF/jasper/reportMaquinaData");
String nome = "c:/teste/reportMaquinaData";
JasperCompileManager.compileReportToFile(nome+".jrxml");
Map<String, Object> parametros = new HashMap<String, Object>();
parametros.put("dataIni", relatorio.getDateIni());
parametros.put("dataFim", relatorio.getDateFim());
parametros.put("tagSrc", "1178345026");
Connection conn = tempMachineDao.retornaCon();
GeradorRelatorioUtil geradorRelatorio = new GeradorRelatorioUtil(nome+".jasper", parametros, conn);
geradorRelatorio.geraPDParaOutputStream(new FileOutputStream(nome+relatorio.getTag()+".pdf"));
return "/relatorio/ok";
}
seria no return? tentei retornar o proprio arquivo do geradorRelatorio, mudei também o metodo para retornar oque ele tinha exportado e não rolou. só continua criando na pasta
tentei da seguinte forma
public byte[] form(@RequestParam("id[]") int id[],
@RequestParam("dateIni") @DateTimeFormat(pattern = "dd/MM/yyyy") Date dateIni,
@RequestParam("dateFim") @DateTimeFormat(pattern = "dd/MM/yyyy") Date dateFim,
@RequestParam("horaInit") String horaInit, @RequestParam("minutoInit") String minutoInit,
@RequestParam("horaFim") String horaFim, @RequestParam("minutoFim") String minutoFim) throws JRException, SQLException, IOException {
Calendar cal = Calendar.getInstance();
Calendar calDateIni = Calendar.getInstance();
calDateIni.setTime(dateIni);
calDateIni.set(Calendar.HOUR_OF_DAY,Integer.valueOf(horaInit));
calDateIni.set(Calendar.MINUTE,Integer.valueOf(minutoInit));
Calendar calDateFim = Calendar.getInstance();
calDateFim.setTime(dateFim);
calDateFim.set(Calendar.HOUR_OF_DAY,Integer.valueOf(horaFim));
calDateFim.set(Calendar.MINUTE,Integer.valueOf(minutoFim));
Relatorio relatorio = new Relatorio();
relatorio.setTag((int) cal.getTimeInMillis());
relatorio.setMachinesIds(id);
relatorio.setDateIni(calDateIni.getTime());
relatorio.setDateFim(calDateFim.getTime());
System.out.println(relatorio.toString());
for (int i = 0; i < relatorio.getMachinesIds().length; i++) {
TemporaryMachineId tempMachine = new TemporaryMachineId();
tempMachine.setMachineId(relatorio.getMachinesIds()[i]);
tempMachine.setTag(relatorio.getTag());
tempMachineDao.gravar(tempMachine);
}
//String nome = request.getServletContext().getRealPath("/WEB-INF/jasper/reportMaquinaData");
String nome = "c:/teste/reportMaquinaData";
JasperCompileManager.compileReportToFile(nome+".jrxml");
Map<String, Object> parametros = new HashMap<String, Object>();
parametros.put("dataIni", relatorio.getDateIni());
parametros.put("dataFim", relatorio.getDateFim());
parametros.put("tagSrc", "1178345026");
Connection conn = tempMachineDao.retornaCon();
GeradorRelatorioUtil geradorRelatorio = new GeradorRelatorioUtil(nome+".jasper", parametros, conn);
return geradorRelatorio.geraPDParaOutputStream();
}
troquei por byte[]
e no metodo fiz o seguinte.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
JasperPrint jasperPrint = JasperFillManager.fillReport(this.nomeArquivo, this.parametros, this.connection);
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
exporter.setConfiguration(configuration);
exporter.exportReport();
outputStream.close();
return outputStream.toByteArray();
} catch (JRException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return outputStream.toByteArray();
}
retornei um bytearray;
deu o seguinte erro.
java.lang.IllegalArgumentException: Unknown return value type [[B]
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:70)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
fiz uma alteração mas ainda nao funciona. Acho que dessa vez cheguei mais perto do resultado.
@Controller
public class RelatorioController {
@Autowired
private HttpServletRequest request;
@Autowired
private TemporaryMachineIdDao tempMachineDao;
@ResponseBody
@RequestMapping(value = "/report/relatorio", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public void form(@RequestParam("id[]") int id[],
@RequestParam("dateIni") @DateTimeFormat(pattern = "dd/MM/yyyy") Date dateIni,
@RequestParam("dateFim") @DateTimeFormat(pattern = "dd/MM/yyyy") Date dateFim,
@RequestParam("horaInit") String horaInit, @RequestParam("minutoInit") String minutoInit,
@RequestParam("horaFim") String horaFim, @RequestParam("minutoFim") String minutoFim,
HttpServletResponse response) throws JRException, SQLException, IOException {
Calendar cal = Calendar.getInstance();
Calendar calDateIni = Calendar.getInstance();
calDateIni.setTime(dateIni);
calDateIni.set(Calendar.HOUR_OF_DAY,Integer.valueOf(horaInit));
calDateIni.set(Calendar.MINUTE,Integer.valueOf(minutoInit));
Calendar calDateFim = Calendar.getInstance();
calDateFim.setTime(dateFim);
calDateFim.set(Calendar.HOUR_OF_DAY,Integer.valueOf(horaFim));
calDateFim.set(Calendar.MINUTE,Integer.valueOf(minutoFim));
Relatorio relatorio = new Relatorio();
relatorio.setTag((int) cal.getTimeInMillis());
relatorio.setMachinesIds(id);
relatorio.setDateIni(calDateIni.getTime());
relatorio.setDateFim(calDateFim.getTime());
System.out.println(relatorio.toString());
for (int i = 0; i < relatorio.getMachinesIds().length; i++) {
TemporaryMachineId tempMachine = new TemporaryMachineId();
tempMachine.setMachineId(relatorio.getMachinesIds()[i]);
tempMachine.setTag(relatorio.getTag());
tempMachineDao.gravar(tempMachine);
}
//String nome = request.getServletContext().getRealPath("/WEB-INF/jasper/reportMaquinaData");
String nome = "c:/teste/reportMaquinaData";
JasperCompileManager.compileReportToFile(nome+".jrxml");
Map<String, Object> parametros = new HashMap<String, Object>();
parametros.put("dataIni", relatorio.getDateIni());
parametros.put("dataFim", relatorio.getDateFim());
parametros.put("tagSrc", "1178345026");
Connection conn = tempMachineDao.retornaCon();
GeradorRelatorioUtil geradorRelatorio = new GeradorRelatorioUtil(nome+".jasper", parametros, conn);
byte [] data = geradorRelatorio.geraPDParaOutputStream();
streamReport(response, data, "report.pdf");
}
protected void streamReport(HttpServletResponse response, byte[] data, String name)
throws IOException {
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=" + name);
response.setContentLength(data.length);
response.getOutputStream().write(data);
response.getOutputStream().flush();
}
}
o botao tem essa seguinte chamada em ajax. nao seis e é este o problema.
$('#criaRelatorio').click(
function() {
var dataIni = $('#dateIni').val();
var objDateIni = new Date();
objDateIni.setYear(dataIni.split("/")[2]);
objDateIni.setMonth(dataIni.split("/")[1]);
objDateIni.setDate(dataIni.split("/")[0]);
var dateFim = $('#dateFim').val();
var objDateFim = new Date();
objDateFim.setYear(dateFim.split("/")[2]);
objDateFim.setMonth(dateFim.split("/")[1]);
objDateFim.setDate(dateFim.split("/")[0]);
if (objDateIni.getTime() > objDateFim.getTime()) {
alert('dataIni menor que data Fim');
}
if (objDateIni.getTime() == objDateFim.getTime()) {
var horaInit = $('#horaInit option:selected')
.text()
+ $('#minutoInit option:selected').text();
var horaFim = $('#horaFim option:selected').text()
+ $('#minutoFim option:selected').text();
if (horaInit > horaFim) {
alert('horaIni maior que horaFim');
}
} else {
var ids = [];
$(':checkbox:checked').each(function(i) {
ids[i] = $(this).val();
});
if (ids == 0) {
alert("selecione alguma maquina");
} else {
var horaInit = $('#horaInit option:selected').val();
var minutoInit = $('#minutoInit option:selected').val();
var horaFim = $('#horaFim option:selected').val();
var minutoFim = $('#minutoFim option:selected').val();
var dateFim = $('#dateFim').val();
var dateIni = $('#dateIni').val();
$.ajax({
url : 'report/relatorio',
method : 'POST',
data : {
id : ids,
dateIni:dateIni,
dateFim:dateFim,
horaInit:horaInit,
minutoInit:minutoInit,
horaFim:horaFim,
minutoFim:minutoFim
},
success : function() {
}
});
}
}
Já tentou JasperExportManager.exportReportToPdfFile
??
Boa Tarde
denisspitfire,
Dependendo no nível de compatibilidade que você deseja ter é melhor salvar em arquivo, pois ja vi vários problemas em relação do javascript com safari por exemplo. Salvando o arquivo em disco você retorna uma url de onde ele fica e se tiver uma demanda alta você pode configurar o apache para servir ele.
att