Error in creating PDF using jaspersoft ireport - java

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

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

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.

set content header name in response in 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();

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.

DynamicJasper - subreport not displaying

i'm new to DynamicJasper.
I'm building a report that contain a subreport, i can run my original report successfully without any error, but the subreport is not displaying.
I'm using DynamicReportBuilder(drb) for building my main report, i'm wondering i'm adding my subreport in the wrong way.
Below is how i build my subreport
private DynamicReport subReportTesting() throws Exception
{
DynamicReportBuilder drb = new DynamicReportBuilder();
DynamicReport dr = drb.addColumn(subAbstractColumn1)
.addColumn(subAbstractColumn2)
.addColumn(subAbstractColumn3)
.setPrintColumnNames(true)
.setIgnorePagination(true)
.setMargins(0, 0, 0, 0)
.setTitle("Sales Report")
.setSubtitle("This report was generated at " + new Date())
.setUseFullPageWidth(true)
.build();
return dr;
}
and here is how i add my main report and subreport.
public DynamicReport buildReport() throws Exception {
{
DynamicReportBuilder drb = new DynamicReportBuilder();
drb.setTitle("This is original report")
.setSubtitle("This is subtitle")
.setMargins(15, 15, 15, 15)
.setUseFullPageWidth(true);
.setDetailHeight(30);
.setAllowDetailSplit(true);
.addColumn(mainAbstractColumn1);
.addColumn(mainAbstractColumn2);
.addColumn(mainAbstractColumn3);
DynamicReport myDynamicReport = new DynamicReport();
try {
myDynamicReport = subReportTesting();
} catch (Exception e) {
e.printStackTrace();
}
SubReportBuilder srb = new SubReportBuilder();
srb.setDynamicReport(myDynamicReport, new ClassicLayoutManager());
try {
mySubReport = srb.build();
**drb.addConcatenatedReport(mySubReport);**
} catch (DJBuilderException e) {
e.printStackTrace();
}
DynamicReport myMainReport = drb.build();
return myMainReport;
}
My contents is add by using preparedStatement and HashMap.
I expect the subreport will display it's title, subtitle and column header even there is no data to be show in the subreport's content, but currently it show nothing about the subreport.
Please correct me if i make any mistake.
Thank you so much.
I recommend you this http://dynamicjasper.com/docs/current/xref-test/ar/com/fdvs/dj/test/MultiReportConcatenated.html

Categories