Problem using Java with ireport - java

try {
//providing path of jrxml to java
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ReportTemplates/WeeklyReportForCurrentWeek.jrxml");
JasperDesign jdesign = JasperManager.loadXmlDesign(inputStream);
String imgPath = "C:/Users/Sorathiya.Deven/";
//Compile managaer
JasperReport jreport = JasperManager.compileReport(jdesign);
//Run time Report parameters
Map param = new HashMap();
param.put("CurrWeek", new java.math.BigDecimal(week));
param.put("CurrYear", new java.math.BigDecimal(year));
param.put("imgPath", imgPath);
//Fatch Database
Connection con = CreateConnection.makeConnection();
//compile report
JasperPrint jprint=JasperFillManager.fillReport(jreport, param, con);
JRPdfExporter exporterPDF = new JRPdfExporter();
exporterPDF.setParameter(JRExporterParameter.JASPER_PRINT, jprint);
exporterPDF.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "C:/Users/Sorathiya.Deven/WeeklyReportForCurrentWeek.pdf");
exporterPDF.exportReport();
CreateConnection.closeConnection(con);
} catch (Exception e) {
e.printStackTrace();
}
Hello friends i am using above given code for showing my report containing sub report but when i run this i get report containing blank page does any one tell me whats the actual problem

Your connection is empty.
Please parse sql query then create the report.

Related

Export to Excel: Ho to prevent splitting data in Last Page Footer

I have a problem, i generate XLSX with JasperReports, but if i want print document, he's break page not correctly.
I need last page footer not split.
I can't use ignorePagination or ignoreMargins, because they delete space (delete page break) and my last page footer split on another page...
Split type on last page footer set Prevent
What do you recommend to me?
JasperReports library - 6.3.0
iReport - 5.6.0
Java - 1.8
MS Excel - 2016
My report design:
The generated XLSX file looks like:
You can see, if page break move on 1 cell down, page print correctly, but i can't open every document for correction him
The splitType for lastPageFooter is set as Prevent.
Java code
public void createReport(Map<String,Object> dataMap, HttpServletResponse response, HttpServletRequest request){
String pathToServletRoot = request.getSession(true).getServletContext().getRealPath("/");
String sourceFileName = pathToServletRoot + "/resources/template/jasper/reportT12.jasper";
try {
ArrayList<DataBean> dataList = dataBeanArrayList(dataMap);
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
Map parameters = new HashMap();
try {
JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName,
parameters, beanColDataSource);
JRXlsxExporter exporter = new JRXlsxExporter();
ByteArrayOutputStream xlsxReport = new ByteArrayOutputStream();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(xlsxReport));
SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration();
configuration.setOnePagePerSheet(false);
configuration.setDetectCellType(true);
exporter.setConfiguration(configuration);
exporter.exportReport();
response.getOutputStream().write(xlsxReport.toByteArray());
} catch (JRException e) {
e.printStackTrace();
}
} catch(Exception ex) {
CrmLogger.error(ex);
}
}

Java Call JasperReports print issue

I have made an application in Java. For the application bill receipt is required and I have used JasperReports (.jrxml ) file.
I have used JasperReports call in Java code for the generating bill.
When I click on print bill the print is not proper, size is reduced.
Actually the problem is strange. I am working on desktop computer and when I print from it , the print is ok.. but when I move my project to other system (say, Laptop) The print I get is approx 50% reduced than the original print. Is there any problem with iReport?
I have used below Java code:
public static void main(String[] args) throws JRException,
ClassNotFoundException, SQLException {
String reportSrcFile = "F:/Bills/FirstJasperReport.jrxml";
// First, compile jrxml file.
JasperReport jasperReport = JasperCompileManager.compileReport(reportSrcFile);
Connection conn = ConnectionUtils.getConnection();
// Parameters for report
Map<String, Object> parameters = new HashMap<String, Object>();
JasperPrint print = JasperFillManager.fillReport(jasperReport,
parameters, conn);
// Make sure the output directory exists.
File outDir = new File("C:/jasperoutput");
outDir.mkdirs();
// PDF Exportor.
JRPdfExporter exporter = new JRPdfExporter();
ExporterInput exporterInput = new SimpleExporterInput(print);
// ExporterInput
exporter.setExporterInput(exporterInput);
// ExporterOutput
OutputStreamExporterOutput exporterOutput = new SimpleOutputStreamExporterOutput(
"C:/jasperoutput/FirstJasperReport.pdf");
// Output
exporter.setExporterOutput(exporterOutput);
//
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
exporter.setConfiguration(configuration);
exporter.exportReport();
System.out.print("Done!");
}
How to resolve this issue
I was facing the same issue. It is kind weird but when I search at Jasper Community I had found the solution
The code solved the problem
PrintRequestAttributeSet printRequestAttrs = new HashPrintRequestAttributeSet();
printRequestAttrs.add(new PrinterResolution(600, 600, ResolutionSyntax.DPI)); // this resolution solved the problem
JRPrintServiceExporter exporter = new JRPrintServiceExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, report);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, printRequestAttrs);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.TRUE);
exporter.exportReport();
Hope this will help!
Have you tried checking the printer properties before printing? Maybe The size of your report template does not match with the paper size set on the printer.

How to insert two pages in report

I´m facing one problem, I have two jrmxl files. I want to join then in one pdf file, but each in one page.
I saw some tips below but I don´t know if they are the best, because my first file have 3 bands: title, detail and summary. The second have detail and summary.
So I want to keep this format if is possible, because in the summary have the page counter.
I´ve tried this but my second page is blank and have 5 cm of heigth.
List pages = new ArrayList<>();
for (String caminhoRelatorio : caminhoRelatorios) {
reportPath = JasperCompileManager.compileReport(caminhoRelatorio);
reportPage = JasperFillManager.fillReport(reportPath, parameters, ds);
pages.add(reportPage);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JRPdfExporter jrPdfExporter = new JRPdfExporter();
jrPdfExporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, pages);
jrPdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
jrPdfExporter.setParameter(JRPdfExporterParameter.IS_CREATING_BATCH_MODE_BOOKMARKS, Boolean.TRUE);
jrPdfExporter.exportReport();
So what I need to do?
To add multiple JRXMLs in one report/PDF, you can follow the below mentioned way:
Consider the method below to generate a PDF report with 2 JRXMLs which have added in the "jrxmlFileNames" list
public static void reportGenerator(String reportType, List<String> jrxmlFileNames,
Datasource dataSource , String SwapFile)
{
JRConcurrentSwapFile swapFile = new JRConcurrentSwapFile(SwapFile, 102400 , 10);
JRAbstractLRUVirtualizer virtualizer = new JRSwapFileVirtualizer(1000, swapFile, true);
Map<String, JRAbstractLRUVirtualizer> parameters = new HashMap<String, JRAbstractLRUVirtualizer>();
parameters.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
try
{
if (reportType.equalsIgnoreCase("PDF"))
{
try
{
JasperReport jreport1 = JasperCompileManager.compileReport(ReportGenerator.class.getResourceAsStream(jrxmlFileNames.get(0)));
JasperPrint jprint1 = JasperFillManager.fillReport(jreport1, parameters, new JRBeanCollectionDataSource(dataSource.getDataSourceFor1()));
JasperReport jreport2 = JasperCompileManager.compileReport(ReportGenerator.class.getResourceAsStream(jrxmlFileNames.get(1)));
JasperPrint jprint2 = JasperFillManager.fillReport(jreport2, parameters, new JRBeanCollectionDataSource(dataSource.getDataSourceFor2()));
List<JasperPrint> jprintlist = new ArrayList<JasperPrint>();
jprintlist.add(jprint1);
jprintlist.add(jprint2);
String fileName="TESTReport.pdf";
JRExporter exporter = new JRPdfExporter();
exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT_LIST, jprintlist);
exporter.setParameter(JRPdfExporterParameter.OUTPUT_FILE_NAME, fileName);
exporter.exportReport();
}
catch(Exception e)
{
e.printStackTrace();
}
}
swapFile.dispose();
}
catch(Exception e)
{
e.printStackTrace();
}
}
In the above code the following part will help you adding the multiple JRXMLs
List<JasperPrint> jprintlist = new ArrayList<JasperPrint>();
jprintlist.add(jprint1);
jprintlist.add(jprint2);
JRExporter exporter = new JRPdfExporter();
exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT_LIST, jprintlist);
Hope it helps!
To get two pages in report you can use Report group and delete all other bands like detail, summary.
To add report group :-
1:- Open report and in Report inspector right click and select "Add Report Group".
2:- Give any name and choose "Group by the following expression" radio button and leave the expression blank and then Next, select only Report header and then finish.
3:- Now for the second page you can add one more Report Group in the same way.
Here there is a similar question: How do i add a second page on Jaspersoft iReport designer. There is also a simpler way: Put a Page Break component on your Detail Band, which means, drag and drop a 'Break' component, and on the popUp that will get displayed select "Page Break"

JasperReports: getting java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number

I am trying to generate excel reports from Java. I am using Spring on Java side and iReport to develop the jasper files. I am getting ClassCast exception although the report runs fine on iReport. The language I am using at iReport side for report is Java.
The whole error Console is:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number
at net.sf.jasperreports.engine.JRAbstractExporter.getNumberCellValue(JRAbstractExporter.java:1198)
at net.sf.jasperreports.engine.JRAbstractExporter.getTextValue(JRAbstractExporter.java:1139)
at net.sf.jasperreports.engine.export.JRXlsExporter.createTextCell(JRXlsExporter.java:737)
at net.sf.jasperreports.engine.export.JRXlsExporter.exportText(JRXlsExporter.java:684)
at net.sf.jasperreports.engine.export.JRXlsAbstractExporter.exportPage(JRXlsAbstractExporter.java:1195)
at net.sf.jasperreports.engine.export.JRXlsAbstractExporter.exportReportToStream(JRXlsAbstractExporter.java:940)
at net.sf.jasperreports.engine.export.JRXlsAbstractExporter.exportReport(JRXlsAbstractExporter.java:629)
at com.ultimatix.dao.SubmissionReportJasperDaoImpl.mainReportXLS(SubmissionReportJasperDaoImpl.java:590)
at com.ultimatix.service.SubmissionReportJasperServiceImpl.excelDownload(SubmissionReportJasperServiceImpl.java:159)
Is there some mismatch of data types within the report or some other issue. Since iReport generates the o/p, I have no clue what is wrong at Java end.
My Implementation:
String mainDir="D:/Reports _ B_Type/";
String[] sheetNames={"Contract Details","Quick Selection","Basic Details","Billing Related Parameter","Discounts Applicable","Charges Applicable","Other Parameter","Slab-Wise Rates"};
Map<String, Object> parameters = new HashMap<String, Object>();
contractId = (String) contractData.get(DBConstants.PROC_PI_CONTRACT_ID);
versionNo = (String) contractData.get(DBConstants.VERSION_NO);
String sql=SQLQuery.getCommonHeaderDetailForFCmVersion();
ByteArrayOutputStream os1 = new ByteArrayOutputStream();
try
{
jdbcTemplate = new JdbcTemplate(dataSource);
contractDataList = jdbcTemplate.queryForList(sql,new Object[] {contractId,versionNo});
for (Map<String,Object> row : contractDataList) {
contractingCompany=(String) row.get(DBConstants.FCM_CONTRACT_INFO_CONTRACTING_COMPANY);
customerName=(String) row.get(DBConstants.FCM_CONTRACT_INFO_MV_CUSTOMER_NAME);
startDate=(String) row.get(DBConstants.FCM_CONTRACT_INFO_MV_CONTRACT_START_DATE);
endDate=(String) row.get(DBConstants.FCM_CONTRACT_INFO_MV_CONTRACT_END_DATE);
if(null != row.get(DBConstants.FCM_CONTRACT_INFO_MV_TOTAL_CONTRACT_VALUE))
{
tcsContractValue= row.get(DBConstants.FCM_CONTRACT_INFO_MV_TOTAL_CONTRACT_VALUE).toString();
}
contractStatus="E";
}
/*parameters to be passed in report */
parameters.put("ContractId", contractId);
parameters.put("VersionNo", versionNo);
parameters.put("SUBREPORT_DIR",mainDir);
parameters.put("ContractingCompany",contractingCompany);
parameters.put("CustomerName",customerName);
parameters.put("StartDate",startDate);
parameters.put("EndDate",endDate);
parameters.put("TcsContractValue",tcsContractValue);
parameters.put("ContractStatus",contractStatus);
connection = DataSourceUtils.getConnection(dataSource);
String reportTemplatePath = null;//path to find the template report
String fileSep = File.pathSeparator;
if(fileSep.equals(":") ){
}else{
reportTemplatePath =mainDir + "Main Report.jasper";
}
JasperPrint jasperPrint;
jasperPrint = JasperFillManager.fillReport(
reportTemplatePath,parameters,connection);
JRXlsExporter exporterXLS = new JRXlsExporter();
exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
exporterXLS.setParameter(
JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.FALSE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.SHEET_NAMES,sheetNames);
exporterXLS.setParameter(
JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
exporterXLS.setParameter(
JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.TRUE);
exporterXLS.setParameter(
JRXlsExporterParameter.CREATE_CUSTOM_PALETTE,Boolean.TRUE);//to generate closest matching color when report generated from java end.
try{
exporterXLS.setParameter(JRExporterParameter.OUTPUT_STREAM, os1);
**exporterXLS.exportReport();**
}
catch(Exception e)
{
e.getMessage();
e.printStackTrace();
}`enter code here`
This is where i get the exception.
Sounds like a bug that's been fixed at JasperReports trunk revision 6340.
Build a JasperReports jar from the SVN trunk (or patch the 5.0.1 sources) to check if it's the same problem.

JasperReport, show and print report

I exported a .jrprint file created with iReport.
Now I want to preview the report and finally print it, how can I do this?
I'm trying with:
JRBeanCollectionDataSource ds=new JRBeanCollectionDataSource(list);
JasperPrint jrprint=JasperFillManager.fillReport("report.jrprint", null, ds);
But I have this exception
java.lang.ClassCastException: net.sf.jasperreports.engine.JasperPrint cannot be cast to net.sf.jasperreports.engine.JasperReport
You're specifying the JasperPrint file and not the JasperReport file. Let me break down the files and what they are:
report.jrxml - An xml definition of a jasper report - this defines a report, but cannot be used directly to generate output.
report.jasper - A compiled jrxml file (JasperReport). This can be used as input to fill the report with data.
report.jprint - A report that's been filled with data, and is ready to be exported to multiple output formats
Here's some code to start with the jrxml file the designer creates to get you to an printed pdf output:
Connection connection = PersistenceSessionFactory.getSqlSession().getConnection();
JasperReport report = JasperCompileManager.compileReport( "FancyPantsReport.jrxml" );
// setup parameters for use with the report
HashMap<String, Object> params = new HashMap<String,Object>();
params.put( "sqlDate", fromDate );
// Fill the report data from the sql connection and parameters
JasperPrint printedReport = JasperFillManager.fillReport(report, params, connection);
String outputFilename = "FancyPants-" + dateString + ".pdf";
JasperExportManager.exportReportToPdfFile( printedReport, outputFilename );
LOG.info("Report Generated in " + (System.currentTimeMillis() - start) + "ms");
Notice it uses the compile to get a JasperReport from the jrxml, then the FillManager to get a JasperPrint from the JasperReport, and finally exports the JasperPrint to pdf.
You can use Jasper viewer to preview reports and print it.
Here is an example!
public void generateReport() throws PrinterException {
try {
String sourceFileName = "src/bill/report.jasper";
String printFileName = null;
Purchase_BeanFactory DataBean = new Purchase_BeanFactory();
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(DataBean.generateCollection());
Map parameters = new HashMap();
printFileName = JasperFillManager.fillReportToFile(
sourceFileName,
parameters,
beanColDataSource);
JasperViewer jv=new JasperViewer("src/bill/report.jrprint", false, false);
//set title for the jasper viewer
jv.setTitle("Your Title");
jv.setVisible(true);
//set icon to the jasper viewer
jv.setIconImage(
(new
ImageIcon(getClass().getResource("path/to/image.png")).getImage()));
} catch (Exception e) {
System.out.println("e");
}
}
if you want to print a JasperReport you have to call the fillReport with a JasperReport file (*.jasper).
If you want to get an PDF file you may use following source:
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE, outFile);
exporter.exportReport();
jp is here your *.jrprint file.
You can use the following to produce and print the report:
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);
InputStream jasperStream = YourClass.class.getResourceAsStream(TEMPLATE_BASE_PATH);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperStream, parameters, dataSource);
JasperViewer viewer = new JasperViewer(jasperPrint, false);
viewer.setVisible(true);

Categories