JasperReport, show and print report - java

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

Related

Java merge two Jasper Report

I have created two report jrxml with jasper report. In my java program I merge the two report into one PDF with iText.
The problem is that the pdf contains only one report plus a blank page.
I have also done this proof:
in my java program creation report one creation report two, merge and I see pdf containig only report one plus blank page
in my java program creation report two and then creation report one, merge and I see pdf containing only report two plus blank page
I have to obtain the pdf with both reports
Does someone help me to solve the problem?
Thanks in advance
Attach the code of my java program:
#Name("pdfFactory")
public class PdfScalareFactory {
private static final String JASPER_FILE_MOVIMENTI = "scalarePdf/pdf_movimenti.jrxml";
private static final String JASPER_FILE_SCALARE = "scalarePdf/pdf_scalare.jrxml";
#SuppressWarnings("rawtypes")
public byte[] rawPdf(BeScalare beScalare, String codTabulato, String output) throws JRException, IOException {
JRBeanArrayDataSource dataSource = new JRBeanArrayDataSource(new Object[]{beScalare});
//report's list
List<byte[]> pdfFilesAsByteArray = new ArrayList<byte[]>();
//Report one
Class cScalare = this.getClass();
ClassLoader clScalare = cScalare.getClassLoader();
InputStream isScalare = clScalare.getResourceAsStream(JASPER_FILE_SCALARE);
JasperDesign jasDesignScalare = JRXmlLoader.load(isScalare);
//compile report one
JasperReport reportScalare = JasperCompileManager.compileReport(jasDesignScalare);
//parameters report one
Map<String, Object> paramScalare = new HashMap<String, Object>();
JRBeanCollectionDataSource itemsScalareSaldiPerValuta = new JRBeanCollectionDataSource(beScalare.getLstBeScalareSaldiPerValuta());
paramScalare.put("scalareSaldiPerValuta", itemsScalareSaldiPerValuta);
//fill report one
JasperPrint jasperPrintScalare = JasperFillManager.fillReport(reportScalare, paramScalare, dataSource);
pdfFilesAsByteArray.add(JasperExportManager.exportReportToPdf(jasperPrintScalare));
//Report two
Class c = this.getClass();
ClassLoader cl = c.getClassLoader();
InputStream is = cl.getResourceAsStream(JASPER_FILE_MOVIMENTI);
JasperDesign jasDesign = JRXmlLoader.load(is);
//compile report two
JasperReport reportMovimenti = JasperCompileManager.compileReport(jasDesign);
//parameters report two
Map<String, Object> paramMovimenti = new HashMap<String, Object>();
BufferedImage imgNumeroVerde = ImageIO.read(getClass().getResource("/scalarePdf/headphones.png"));
paramMovimenti.put("numeroVerde", imgNumeroVerde);
BufferedImage imgInternet = ImageIO.read(getClass().getResource("/scalarePdf/internet.png"));
paramMovimenti.put("internet", imgInternet);
JRBeanCollectionDataSource itemsScalareMovimenti = new JRBeanCollectionDataSource(beScalare.getLstBeScalareMovimenti());
paramMovimenti.put("scalareMovimenti", itemsScalareMovimenti);
//fill report two
JasperPrint jasperPrintMovimenti = JasperFillManager.fillReport(reportMovimenti, paramMovimenti, dataSource);
pdfFilesAsByteArray.add(JasperExportManager.exportReportToPdf(jasperPrintMovimenti));
//merge the two reports in one
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Document document = null;
PdfCopy writer = null;
for (byte[] pdfByteArray : pdfFilesAsByteArray) {
try {
PdfReader reader = new PdfReader(pdfByteArray);
int numberOfPages = reader.getNumberOfPages();
if (document == null) {
document = new Document(reader.getPageSizeWithRotation(1));
writer = new PdfCopy(document, outStream); // new
document.open();
}
PdfImportedPage page;
for (int i = 0; i < numberOfPages;) {
++i;
page = writer.getImportedPage(reader, i);
writer.addPage(page);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
document.close();
outStream.close();
return outStream.toByteArray();
}
}
Problem is in the data source and not in merging. You create one data source for both reports but the first report will consume it and then the second report has data source with pointer at the end.
You use JRBeanArrayDataSource which implements JRRewindableDataSource so you can call the moveFirst() method to return data source pointer on the first position:
//Report two
dataSource.moveFirst();
Or you can create the data source again for the second report:
//Report two
dataSource = new JRBeanArrayDataSource(new Object[]{beScalare});
Note: But as Amongalen mentioned in the comment it is easier to merge two and more Jasper reports using JRPdfExporter and List<JasperPrint> instance as an input.

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.

jasperreports how to export multiple jrmxl files to a single worksheet

I have one jrxml file that I would like to populate with 3 different datasources. Then I would like to export to an XLS or XLXS file with the 3 reports concatenated together on one sheet.
String input = "C:\\location\\report1.jrxml";
JasperReport jreport = JasperCompileManager.compileReport(input);
JasperPrint jprint1 = JasperFillManager.fillReport(jreport, new HashMap<String, Object>(), new JRBeanCollectionDataSource(getReportData(1)));
JasperPrint jprint2 = JasperFillManager.fillReport(jreport, new HashMap<String, Object>(), new JRBeanCollectionDataSource(getReportData(2)));
JasperPrint jprint3 = JasperFillManager.fillReport(jreport, new HashMap<String, Object>(), new JRBeanCollectionDataSource(getReportData(3)));
List<JasperPrint> jprintlist = new ArrayList<JasperPrint>();
jprintlist.add(jprint1);
jprintlist.add(jprint2);
jprintlist.add(jprint3);
JRXlsxExporter exporter = new JRXlsxExporter();
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
exporter.setParameter(JRXlsExporterParameter.JASPER_PRINT_LIST, jprintlist);
String xlsFile = "C:\\location\\test.xlsx";
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, xlsFile);
exporter.exportReport();
The reports are all generating as I would expect, however in excel they are being generated on 3 different tabs, what I would like is to have them be built one on top of another. How can I merge them in this way?
You could be to wrap the 3 reports as sub reports in a master report and run that one instead. In order to do so you would need to add the logic for which data source to access into the subreport's data source expression.
alternatively you could post process the excel sheet outside JasperReports.

Problem using Java with ireport

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.

Categories