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.
Related
I am exports PDF usgin jasper reports. In develop, it works fine. But when compile the jar, system throws and FileNotFound Exception for "src/main/resources/reports/myJasperReport.jxml"
When I explore the JAR,I came across that the URL for the report is "/BOOT-INF/classes/resports/myJasperReport.jxml"
I found this link to File inside jar is not visible but didn't solve my problem.
Could you help me please?
#Slf4j
#Service
public class ReportService {
private static final String REPORTS_BASE_PATH = "src/main/resources/reports/";
public ByteArrayInputStream exportReport(
String reportFileName,
Integer idCC,
Map<String,Object> parameters
) throws Exception {
Connection connection = CustomEntityManagerFactoryPostgresImpl
.getInstance()
.getConnection(idCC);
File file = ResourceUtils.getFile(REPORTS_BASE_PATH + reportFileName);
JasperReport jasperReport = JasperCompileManager.compileReport(file.getAbsolutePath());
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, connection);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
return new ByteArrayInputStream(outputStream.toByteArray());
}
}
Add classpath: prefix to your path. And consider the resources folder to be a root.
ResourceUtils.getFile("classpath:reports/" + reportFileName);
UPD:
Actually, you don't need to get a file at all. Try to get resource as stream:
InputStream report = ReportService.class.getClassLoader().getResourceAsStream("reports/" + reportFileName);
JasperReport jasperReport = JasperCompileManager.compileReport(report);
I am creating HTTP server with Tomee, i am placed jasper report file (.jasper) in webapp directory. if i access http://localhost:8080/test.jasper in browser, the browser will prompt to download the file.
In my java project i'm creating simple code to access that link and then preview the report. I use async-http-client library for request.
DefaultAsyncHttpClient client = new DefaultAsyncHttpClient();
BoundRequestBuilder brb = client.prepareGet("http://localhost:8765/qa/test.jasper");
Future<InputStream> f = brb.execute(new AsyncCompletionHandler<InputStream>() {
#Override
public InputStream onCompleted(Response resp) {
try {
String[][] data = {{"Jakarta"},{"Surabaya"},{"Solo"},{"Denpasar"}};
String[] columnNames = {"City"};
DefaultTableModel dtm = new DefaultTableModel(data, columnNames);
Map<String,Object> params = new HashMap<>();
JasperPrint jPrint = JasperFillManager.fillReport(
resp.getResponseBodyAsStream(),
params,
new JRTableModelDataSource(dtm)
);
JasperViewer jpView = new JasperViewer(jPrint,false);
jpView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jpView.setSize(800, 600);
jpView.setLocationRelativeTo(null);
jpView.setVisible(true);
} catch (JRException ex) {
System.out.println(ex.getMessage());
}
return resp.getResponseBodyAsStream();
}
});
From my code above, i got an error Error loading object from InputStream
normally i can use
InputStream input = MainContext.class.getResourceAsStream(filename);
But i want to replace file input stream with http request (stream too).
How exactly i can serve .jasper file with http server...?
Error loading object from InputStream error came from corrupt InputStream, if i download .jasper file normally via browser and execute the report with JRLoader.loadObjectFromFile(path to file) it doesn't works too, because tomee give corrupt file (the source file not corrupt).
My own solution is read source file as stream, convert it to base64 encode, and serve it via HTTP API protocol.
finput = new FileInputStream(sPath);
byte[] bFile = Base64.getEncoder().encode(IOUtils.toByteArray(finput));
String sFile = new String(bFile);
inside client side, i received it as body string, decode the base64 string, convert it to InputStream and Finally execute the report with InputStream.
byte[] bBody = Base64.getDecoder().decode(sBody);
InputStream mainReport = new ByteArrayInputStream(bBody);
return JasperFillManager.fillReport(mainReport, params);
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();
}
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
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.