How to display the reports on client side jsp? - java

I am trying to display the result in jsp page. In my In dex.html has a link as ,
Vehicle Report
In vehicleReport.jsp I am displaying report as,
<body>
<%
Connection con=null;
try{
con=VehicleDetails.getConnection();
InputStream inputStream = new FileInputStream ("E:/ReportFld/report4.jrxml");
Map parameters = new HashMap();
JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
#SuppressWarnings("unchecked")
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, con);
out.clear(); // where out is a JspWriter
out = pageContext.pushBody();
JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
}
catch(Exception e){e.printStackTrace();}
finally{
con.close();
}
%>
</body>
But problem is report is not visible. In jsp it displays some unreadable text. and I am getting error message as,
SEVERE: Servlet.service() for servlet [jsp] in context with path [/Reports] threw exception [java.lang.IllegalStateException: getOutputStream() has already been called for this response] with root cause
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:636)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
How to resolve this?

Try using
JasperExportManager.exportReportToPdfFile(JasperPrint jsperPring, String fileName);
instead of
JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
and then display your pdf in browser or anywhere you want.

Related

How to display a Jasper Report inside a HTML page

So, I already have the report made, but the problem is that I'm using GetMapping to display, and it opens on another page alone, but I need it to open on a div, a table, a card, or even a modal. It just can't change from the previous page.
I have no idea how to open it with out redirecting the page. Any suggestion is appreciated
Method on the controller
#GetMapping("/seguro")
public void export(HttpServletResponse response) throws IOException, JRException, SQLException {
response.setContentType("text/html");
JasperPrint jasperPrint = null;
jasperPrint = seguroReportService.generatePromissoria(1L);
HtmlExporter htmlExporter = new HtmlExporter(DefaultJasperReportsContext.getInstance());
htmlExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
htmlExporter.setExporterOutput(new SimpleHtmlExporterOutput(response.getWriter()));
htmlExporter.exportReport();
}
Method to get the report file
public JasperPrint generatePromissoria(Long id) throws SQLException, JRException, IOException {
Connection conn = jdbcTemplate.getDataSource().getConnection();
String path = resourceLoader.getResource("classpath:/reports/SeguroReport.jrxml").getURI().getPath();
JasperReport jasperReport = JasperCompileManager.compileReport(path);
// Parameters for report
Map<String, Object> parameters = new HashMap<>();
parameters.put("titulo", "Relatório de Seguros");
parameters.put("ID", id);
JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, conn);
return print;
}
page where is supposed to open the report
Report opening in another page
I resolve the problem using the Iframe, but instead of passing the HTML on the src="", I made a onClick function on the button from my form targeting the name of the iframe.
<iframe name="my_iframe" src=""></iframe>
<button onclick="this.form.target='my_iframe'">My Button</button>

Jasper report downloading using $http.post not working

I'm using Jasper reporting in my application.
The steps are the basic ones,
response.setHeader("Content-Disposition", "attachment;filename=report.pdf");
response.setContentType("application/pdf");
OutputStream outStream = response.getOutputStream();
InputStream inputStream = new FileInputStream(new File(this.template)); // .jrxml file
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(this.dataList);
JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
JasperExportManager.exportReportToPdfStream(jasperPrint,outStream );
JasperExportManager.exportReportToPdfFile(jasperPrint,"/test.pdf");// this works in any case
I have a form submit in the HTML page.
<form action="{{vm.downloadUrl}}"
id="downloadPdf" name="downloadPdf"
method="post"></form>
The js is, (this will download the pdf without a problem)
vm.downloadUrl = appConfig.baseUrl+'/generateReport2?data='+data;
document.getElementById('downloadPdf').action = vm.downloadUrl;
document.downloadPdf.submit(); // document.form_name.submit();
But when I use the below code it will download an empty pdf, although the PDF created and saved to the local disk from JasperExportManager.exportReportToPdfFile(jasperPrint,"/test.pdf");
$http.post(vm.downloadUrl)
.success(function (response) {
console.log('response received :');
console.log(response);
var file = new Blob([response], { type: 'application/pdf' });
saveAs(file, 'filename.pdf');
});
What can be the issue here. Why is it downloading an empty file. I had an issue earlier similar to this and now it's handled by setting whenNoDataType="AllSectionsNoDetail" in jrxml file.

I can not choose where to save the generated report in Jasper

I have a problem when I click to generate a report ... I would like the moment I clicked the button to generate the report to be shown a window asking where I want to save the document, the way it is now I'm in java code specifying the location and file name, and always the file is saved in the specified place in the code, I do not want it, I need to leave it open for the person to choose where to save ... down goes a piece of code I am using.
.
try {
URL arquivo = getClass().getResource(/reports/term.jasper);
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(arquivo);
//It generates the dto that will be sent to IReport
ArrayList<MinutoTRDto> dataList = getDataBeanList(licitacao);
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
Map<String, Object> parameters = getParametros();
JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
JROdtExporter exporterOdt = new JROdtExporter();
exporterOdt.setExporterInput(new SimpleExporterInput(print));
// HERE IS THE PROBLEM!
exporterOdt.setExporterOutput(new SimpleOutputStreamExporterOutput("C://teste//sample_report.odt"));
exporterOdt.exportReport();
} catch (JRException jre) {
jre.printStackTrace();
}
You will have to write the following in your code
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=<your file name>");
With this, the 'file download' dialog will appear. You can refer here for the complete code.
Following the AMDG replied, I changed my file to the following code, only it was launched the following exception:
org.apache.jasper.JasperException: java.lang.IllegalStateException: getOutputStream() has already been called for this response
I using Wicket from framework
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
URL arquivo = getClass().getResource(REPORT_PATH);
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(arquivo);
ArrayList<MinutoTRDto> dataList = getDataBeanList(licitacao);
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
Map<String, Object> parameters = getParametros();
print = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
JROdtExporter exporterOdt = new JROdtExporter();
exporterOdt.setExporterInput(new SimpleExporterInput(print));
exporterOdt.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
exporterOdt.exportReport();
byte[] bytes = outputStream.toByteArray();
if (bytes != null && bytes.length > 0) {
HttpServletResponse response =(HttpServletResponse)((WebResponse)comp.getResponse()).getContainerResponse();
response.setContentType("application/odt");
response.setHeader("Content-disposition", "inline; filename=\"file_generated.odt\"");
response.setContentLength(bytes.length);
ServletOutputStream outputStream2 = response.getOutputStream();
outputStream2.write(bytes, 0, bytes.length);
outputStream2.flush();
outputStream2.close();
}
} catch (Exception e) {
e.printStackTrace();
}

java pdf file download using ajax request

I am using Spring MVC. I don't want to show my URL in browser, since in am passing the id in it. I am using AJAX request,and I am using jquery.fileDownload.js file from http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/ URL to download file
my javascript code is
function print(value)
{
var myurl='PropertyTaxRegistration.html?PrintReport&assid='+value;
$.fileDownload(myurl, {
successCallback: function (url) {
alert('You just got a file download dialog or ribbon for this URL :' + url);
},
failCallback: function (html, url) {
alert('Your file download just failed for this URL:' + url + '\r\n' +
'Here was the resulting error HTML: \r\n' + html
);
} }); }
and my java code is
JasperDesign jasperDesign = JRXmlLoader.load(jrxmlFileLocation);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, new JRBeanCollectionDataSource(dataCollection));
response.setContentType("application/pdf");
JasperExportManager.exportReportToPdfStream(jasperPrint, (OutputStream) response.getOutputStream());
//JasperExportManager.exportReportToPdfStream(jasperPrint, (OutputStream) response.getOutputStream());
response.setContentType("application/pdf");
response.getOutputStream().flush();
response.getOutputStream().close(); return true;
My going in java class properly.
but in each each case it is going in error i.e,failCallback function and give error message;
Please help with my error.
Thanks in advance

pdf download dialog window not appear in browser. extjs 4 with java

I am able to generate a report in pdf form using JasperReports and Java.
The generated report is not available to be downloaded to the client side.
I am generating pdf file using the code below:
public void getTaskreportPDF(Session openSession,HttpServletRequest request,HttpServletResponse response) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/contact","root","root");
Map params = getParameters(openSession);
Date date = new Date();
String reportfileName = "report"+date.getDate()+"-"+date.getMonth()+"-"+date.getYear()+"-"+date.getTime()+".pdf";
JasperDesign jasperDesign = JRXmlLoader.load(this.getClass().getResourceAsStream("/com/gantt/report/ganttreport.jrxml"));
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperprint = JasperFillManager.fillReport(jasperReport, params,con);
JRAbstractExporter exporterPDF = new JRPdfExporter();
exporterPDF.setParameter(JRExporterParameter.JASPER_PRINT, jasperprint);
exporterPDF.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
response.setHeader("Content-Disposition", "inline;filename="+ reportfileName);
response.setContentType("application/pdf");
exporterPDF.exportReport();
} catch(Exception exception) {
System.out.println("Error occured " +exception.getMessage());
}
}
My firebug net tab shows that I had got the pdf report file of 4 kb as response. But the problem is that download window not appear, so I cannot save it or view that report.
My firebug shows:
Content-Disposition inline;filename=report21-0-112-1327135412907.pdf
Content-Type application/pdf
What mistake I am making which makes my download window not to appear?
Use attachment instead of inline for the Content-Disposition header.

Categories