java pdf file download using ajax request - java

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

Related

How to display DynamicReports in browser without download to cliend drive?

I have to display some reports with Dynamic Reports. I use NetBeans and Tomcat 7. Eventually, all must be uploaded to cloud OpenShift. I used DynamicReports to create simple report (code snippet):
Connection conn=null;
try {
Class.forName(DBConnStrings.driver);
conn = DriverManager.getConnection(DBConnStrings.url + DBConnStrings.dbName+DBConnStrings.sslState, DBConnStrings.userName, DBConnStrings.password);
} catch (Exception e) {
e.printStackTrace();
}
JasperReportBuilder report = DynamicReports.report();
report
.columns(
Columns.column("Tank Id", "id", DataTypes.integerType()),
Columns.column("Tank Name", "name", DataTypes.stringType()),
Columns.column("Label", "label", DataTypes.stringType()),
Columns.column("Description", "descrshort", DataTypes.stringType()));
report.setDataSource("SELECT id, name, label, descrshort FROM "+ DBConnStrings.dbName +".tbltankslist", conn);
try {
//show the report
//report.show();
//export the report to a pdf file
report.toPdf(new FileOutputStream("c:/report.pdf"));
} catch (DRException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
This code located in a Servlet. It works. I get JasperViewer at first and a report.pdf on my HDD. But I don't want it. First I do not want to see JasperViewer, second I do not want to download file to client HDD. How to display report inside web-browser only?
Here is the question Jasper Reports. It is about jasper reports + iReport and I have no idea how to use that information for DynamicReports - at first, second there is also "download pdf to client drive" approach, but I need to show it inside the browser.
use the following code in your file which redirect towards jasper invocation page, so that your jasperPDF should open in new tab instead of downloading.
JasperInvocation.jsp => file in which you invoke jasperReport
<form method="POST" action="JasperInvocation.jsp" target="_blank">
Please find following code , I have implemented in Dynamic report(Jasper Api) , Its working for me :-
#RequestMapping(value="/pdfDownload", method = RequestMethod.GET)
public void getPdfDownload(HttpServletResponse response) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
report().columns().setDataSource().show()
.toPdf(buffer);
byte[] bytes = buffer.toByteArray();
InputStream inputStream = new ByteArrayInputStream (bytes);
IOUtils.copy(inputStream, response.getOutputStream());
response.setHeader("Content-Disposition", "attachment; filename=Accepted1.pdf");
response.flushBuffer();
}

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();
}

How to display the reports on client side jsp?

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.

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