set content header name in response in java - java

I write this following code to write jasper report in rtf format.It works well, but it open or save with default name file.rtf.
I want to set the name as Report name.
oConn = oPool.getConnection();
ServletContext sServletContext = request.getSession().getServletContext();
String sReportPath = sServletContext.getRealPath(sFileName);
JasperReport jReport = (JasperReport) JRLoader.loadObject(sReportPath);
JasperPrint jPrint = JasperFillManager.fillReport(jReport, hParameters, oConn);
request.getSession().setAttribute(BaseHttpServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,jPrint);
response.setContentType("application/rtf");
response.setHeader("Content-disposition","attachment; filename=\"" +sReportName +"\"");
RequestDispatcher oRequestDispatcher = request.getRequestDispatcher("servlets/rtf");
oRequestDispatcher.forward(request, response);

Check public JRViewer - you can create JRViewer(java.lang.String fileName)
or setParameter - reference code
String fname= "fileName.jasper";
JasperPrint print = JasperFillManager.fillReport(yourDir+"jasper/"+fname);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE, fname);
porterParameter.OUTPUT_FILE_NAME, nfl);
exporter.exportReport();

Related

My JasperReport is not creating the report, just a blank page

I'm trying to create a JasperReport with Spring Boot. My endpoint gives me back some byte[] but it's just blank... I don't know what am I doing wrong.
try{
Map<String, Object> extractParams = new HashMap<>();
Marina marina = marinaProvider.findById(marinaId);
MovementPlan movementPlan = this.getMovementPlanById(movementPlanId, marinaId);
extractParams.put("MARINA_NAME", marina.getTradeName());
extractParams.put("MARINA_CNPJ", marina.getCompanyFederalId());
extractParams.put("BOAT_NAME", movementPlan.getBoat().getName());
extractParams.put("BOAT_TYPE", movementPlan.getBoat().getBowType());
extractParams.put("BOAT_MODEL", movementPlan.getBoat().getModelYear());
extractParams.put("BOAT_TIE", movementPlan.getBoat().getTie());
extractParams.put("RESPONSABLE", movementPlan.getNavigationPlan().getResponsible().getName());
extractParams.put("CONTACT_RESPONSABLE", movementPlan.getNavigationPlan().getResponsible().getEmergencyContact());
extractParams.put("SAILOR", "Sem marinheiro");
extractParams.put("CONTACT_SAILOR", "000-0000");
extractParams.put("VACANCY", movementPlan.getBoat().getVacancy().getCode());
extractParams.put("OUTPUT_EXPECTATION", movementPlan.getCurrentMovement().getMovementPlan().getId());
extractParams.put("REPORT_LOCALE", new Locale("pt", "BR"));
InputStream inputStream = this.getClass().getResourceAsStream("/reports/movementReport/MovementPlan.jasper");
JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, extractParams);
return JasperExportManager.exportReportToPdf(jasperPrint);
}catch (JRException e) {
e.printStackTrace();
throw new MarineException("ERROR", "Relatório", "Erro ao gerar plano de movimentação");
}
This is my jrxml: I used DontPad because its too long
Just found out, since I'm already bringing the data, not the JasperSoft queryng it, I need to pass and empty DataSource, so it works just fine:
JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, extractParams, new JREmptyDataSource());

Error in creating PDF using jaspersoft ireport

I am using reactjs, spring-boot, SQL and ireport to generate the PDF reports. So the file is printed. But the data passing to the clientInvoice.jrxml is null. How I am fix this. I have attached the spring-boot value passing(the is referred to the invoiceID here and it is passing from the frontend).
public ResponseEntity generateClientInvoiceByClientInvoiceId(int id) {
try{
File file = ResourceUtils.getFile("classpath:report/clientInvoice.jrxml");
InputStream input = new FileInputStream(file);
// Compile the Jasper report from .jrxml to .japser
JasperReport jasperReport = JasperCompileManager.compileReport(input);
// Get the parameter
Map<String, Object> parameters = new HashMap<>();
parameters.put("invoiceId",id);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JREmptyDataSource());
// Export the report to a PDF file
JasperExportManager.exportReportToPdfFile(jasperPrint, "D://" + id + ".pdf");
return new ResponseEntity<Object>(null, HttpStatus.OK);
}catch (CustomException e){
e.printStackTrace();
CustomErrorResponse errors = new CustomErrorResponse();
errors.setError(e.getMessage());
return new ResponseEntity(errors, HttpStatus.SERVICE_UNAVAILABLE);
}catch (Exception e){
e.printStackTrace();
CustomErrorResponse errors = new CustomErrorResponse();
errors.setError("Error in creating client invoice ");
return new ResponseEntity<>(errors, HttpStatus.SERVICE_UNAVAILABLE);
}
}
Only I have attached the query which I am using in the JRXML.(The query is attached to the JRXML file).
<queryString>
<![CDATA[SELECT cv.`id`,cv.`client_id`,cv.`no_of_boxes` as total_boxes,cv.`sub_total`,cv.`total_weight`, cvi.`selling_price`, SUM(cvi.`weight`),sp.`selling_prawn_category_type`,cv.`shipping_address`,c.company,sc.`category_name`,count(cvi.selling_category_id) as noOfBoxes, cvi.`selling_price`*SUM(cvi.`weight`) as total_price_per_category,cv.date FROM client_invoice cv INNER JOIN client_invoice_item cvi ON cvi.`client_invoice_id` = cv.`id`INNER JOIN `selling_prawn_category_type` sp ON cvi.`selling_category_id` = sp.`id`INNER JOIN `selling_prawn_category` sc ON sc.selling_prawn_category_id = sp.idINNER JOIN `CLIENT` c ON c.id = cv.client_idWHERE cv.`id` =$P{invoiceId} GROUP BY cvi.`selling_category_id`]]>
</queryString>
Please help me quickly as possible to resolve this.
I think that report is empty beacause of:
new JREmptyDataSource()
You can inject DataSource and try something like this:
try (Connection connection = dataSource.getConnection()){
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, prepareParameters(command), connection);
}

Why Jasperreport.engine.JRException error when including zxing qr code on spring-boot app?

Encountered error when compiling jasperreport template jrxml in spring-boot app
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is net.sf.jasperreports.engine.JRException: Errors were encountered when compiling report expressions class file:
1. com.google.zxing.client.j2se.MatrixToImageWriter cannot be resolved to a type
value = com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage( //$JR_EXPR_ID=38$
<---------------------------------------------->
2. com.google.zxing.client.j2se.MatrixToImageWriter cannot be resolved to a type
value = com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage( //$JR_EXPR_ID=38$
<---------------------------------------------->
3. com.google.zxing.client.j2se.MatrixToImageWriter cannot be resolved to a type
value = com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage( //$JR_EXPR_ID=38 <---------------------------------------------->
3 errors
.] with root cause
RestController code;
#RequestMapping(value = "/reports/{format}/{param}", method = RequestMethod.GET)
public void export(ModelAndView model, HttpServletResponse response, #PathVariable("format") String format, #PathVariable("param") String param) throws IOException, JRException, SQLException {
JasperPrint jasperPrint = null;
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", String.format("attachment; filename=file.pdf"));
OutputStream out = response.getOutputStream();
jasperPrint = reportService.exportPdfFile(format, param);
JasperExportManager.exportReportToPdfStream(jasperPrint, out);
}
Service class code is as below;
public JasperPrint exportPdfFile(String format, String param) throws JRException, IOException{
JasperPrint jasperPrint = null;
List<Bean> bean = beanRepository.findJoins(Long.parseLong(param));
String reportPath = resourceLoader.getResource("classpath:templates/template.jrxml").getURI().getPath();
// Compile the Jasper report from .jrxml to .japser
JasperReport jasperReport = JasperCompileManager.compileReport(reportPath);
// Get your data source
JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(bean);
// Add parameters
Map<String, Object> parameters = new HashMap<>();
parameters.put("createdBy", "john Doe");
// Fill the report
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, jrBeanCollectionDataSource);
return jasperPrint;
}
Jrxml code for image component
<image>
<reportElement x="420" y="75" width="134" height="135" uuid="fc315f59-1b66-41ec-afe6-71fc61362073"/>
<imageExpression><![CDATA[com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage(
new com.google.zxing.qrcode.QRCodeWriter().encode("http://localhost:7777/api/reporto/temp/"+$F{isr_id},com.google.zxing.BarcodeFormat.QR_CODE, 300, 300)
)]]></imageExpression>
</image>
Jar libraries that are include on maven import are:
com.google.zxing:core:3.3.0
net.sf.jasperreports:jasperreports:6.4.0
org.apache.tomcat:jasper-jdt:6.0.29

Add CSS to JasperReports' HTML Export

I've created a report with JasperReports 6.4.3 which is normally exported to PDF. Now, I'm trying to export this report to HTML as well.
I don't want to create a HTML file via JasperExportManager, so I'm using JasperReport's HtmlExporter to wirte the report directly into an outputstream.
Her is my code:
public void exportToHtml(OutputStream outputStream, JRDataSource jrDataSource, Map<String, Object> parameter, File reportFile)
throws IOException {
try {
JasperPrint jasperprint = JasperFillManager.fillReport(reportFile.getAbsolutePath(), parameter, jrDataSource);
HtmlExporter exporter = new HtmlExporter();
SimpleHtmlExporterOutput exporterOutput = new SimpleHtmlExporterOutput(outputStream);
Map<String, String> images = Maps.newHashMap();
exporterOutput.setImageHandler(new HtmlResourceHandler() {
#Override
public void handleResource(String id, byte[] data) {
System.err.println("id" + id);
images.put(id, "data:image/jpg;base64," + Base64.encodeBytes(data));
}
#Override
public String getResourcePath(String id) {
return images.get(id);
}
});
exporter.setExporterOutput(exporterOutput);
exporter.setExporterInput(new SimpleExporterInput(jasperprint));
SimpleHtmlExporterConfiguration exporterConfiguration = new SimpleHtmlExporterConfiguration();
exporterConfiguration.setBetweenPagesHtml("<div style='page-break-after:always'></div>");
exporter.setConfiguration(exporterConfiguration);
exporter.exportReport();
} catch (JRException jrException) {
throw new IOException(jrException);
}
}
The output looks good, but I need to add some styles to the HTML output. So I wonder if it is possible to add a reference to a css file to the exported html report.
Similarly to how you are setting the between pages HTML, you could do the same for the header/footer with:
exporterConfiguration.setHtmlHeader("...");
exporterConfiguration.setHtmlFooter("...");
The default HTML code for header is set here and the one for footer is set here.
You need to match the opening/closing tags when modifying any of them.

NoClassDefFoundError when creating dynamic jasper report

I am trying to create a dynamic jasper report. So I tried creating one using an example in the internet. But when I run the program I get an exception:
Exception in thread "main" java.lang.NoClassDefFoundError:
org/apache/commons/digester/Digester at
net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:143)
at com.tfc.cheque.handle.ui.ReportPrint.main(ReportPrint.java:31)
given below is the code I used:
public class ReportPrint {
public static void main(String[] args) throws JRException, IOException {
JasperReport jasperReport = JasperCompileManager.compileReport("data.xml");
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,new HashMap(), new JREmptyDataSource());
JasperExportManager.exportReportToPdfFile(jasperPrint, "sample.pdf");
}
public ReportPrint(){
try {
DynamicReportBuilder dynamicReportBuilder = new DynamicReportBuilder();
// configure report-level settings
dynamicReportBuilder.setReportName("Some");
dynamicReportBuilder.setPageSizeAndOrientation(Page.Page_Letter_Landscape());
// add id column to the report
ColumnBuilder columnBuilderID = ColumnBuilder.getNew();
columnBuilderID.setTitle("ID");
columnBuilderID.setWidth(180);
columnBuilderID.setFixedWidth(true);
columnBuilderID.setColumnProperty("ID", Integer.class.getName(), "#id");
dynamicReportBuilder.addColumn(columnBuilderID.build());
// add name column to report
ColumnBuilder columnBuilderName = ColumnBuilder.getNew();
columnBuilderName.setTitle("Name");
columnBuilderName.setWidth(180);
columnBuilderName.setFixedWidth(true);
columnBuilderName.setColumnProperty("Name", String.class.getName(), "#name");
dynamicReportBuilder.addColumn(columnBuilderName.build());
// add email column to report
ColumnBuilder columnBuilderEmail = ColumnBuilder.getNew();
columnBuilderEmail.setTitle("Email");
columnBuilderEmail.setWidth(180);
columnBuilderEmail.setFixedWidth(true);
columnBuilderEmail.setColumnProperty("Email", String.class.getName(), "#email");
dynamicReportBuilder.addColumn(columnBuilderEmail.build());
// add salary column to report
ColumnBuilder columnBuilderSalary = ColumnBuilder.getNew();
columnBuilderSalary.setTitle("Salary");
columnBuilderSalary.setWidth(180);
columnBuilderSalary.setFixedWidth(true);
columnBuilderSalary.setColumnProperty("Salary", Integer.class.getName(), "#salary");
dynamicReportBuilder.addColumn(columnBuilderSalary.build());
DynamicReport dynamicReport = dynamicReportBuilder.build();
// build a datasource representing the XML file
JRDataSource dataSource = new JRXmlDataSource(new File("data.xml"), "//employee");
// build JasperPrint instance, filling the report with data from datasource created above
JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(
dynamicReport, new ClassicLayoutManager(), dataSource, new HashMap<String, Object>());
// export to the pdf
String pdfFile = Math.round(Math.random() * 100000) + ".pdf";
JRExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, pdfFile);
exporter.exportReport();
} catch(JRException e) {
e.printStackTrace();
}
}
}
I cannot Figure out the problem here. Please help. Thank you.
Here's a screenshot of my class path settings:
Looks like the file commons-digester.jar is missing in your classpath. Download it and add it to the classpath.

Categories