Java Call JasperReports print issue - java

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.

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

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 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.

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

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