JasperReportBuilder HTML row height - java

I am building a report with JasperReportBuilder from a JDBC data source and afterward I export it to HTML by calling the toHtml method with a JasperHtmlExporterBuilder object parameter. I have been trying to get rid of extra space that exists above the text in each of my rows, column header row, and even my title. I have tried everything I can think of and have been searching online to no avail.
It seems most people have the opposite problem: they need to grow their rows to fit their text. I would like to force my rows to be the height of their contents. If that's not possible, I would be happy with restricting the height of my rows.
The HTML exporter appears to be controlling the height of my rows by inserting an image and setting its height.
Any help would be appreciated. Thanks!
Edit: Here is my code.
String imageServletUrl = "images?image=";
StringWriter writer = new StringWriter();
JasperHtmlExporterBuilder htmlExporter = Exporters.htmlExporter(writer);
htmlExporter.setImagesURI(imageServletUrl);
SqlRowSet rowSet = getData(databaseIpAddr, portNumber, databaseName, databaseUser, databasePassword);
JRDataSource ds = createDataSource(rowSet);
JasperReportBuilder builder = DynamicReports.report();
IntegerType intType = DynamicReports.type.integerType();
DateType dateType = DynamicReports.type.dateType();
int rowHeightPx = 20;
TextColumnBuilder<Integer> col1 = col
.column(COL_TITLE_RESULT_NUM, RESULTS_COL_TITLE_RESULT_NUM, intType)
.setWidth(35)
.setFixedHeight(rowHeightPx)
.setStretchWithOverflow(true);
... create other eight columns ...
StyleBuilder titleStyle = stl.style()
.bold()
.setFontSize(22)
.setHorizontalAlignment(HorizontalAlignment.CENTER);
StyleBuilder columnTitleStyle = stl.style()
.bold()
.setAlignment(HorizontalAlignment.CENTER, VerticalAlignment.MIDDLE)
.setBorder(stl.pen1Point());
StyleBuilder columnStyle = stl.style()
.setAlignment(HorizontalAlignment.CENTER, VerticalAlignment.MIDDLE)
.setLineSpacing(LineSpacing.SINGLE)
.setBorder(stl.pen1Point());
TextFieldBuilder<String> titleBuilder = DynamicReports.cmp
.text(selectedAgency)
.setStyle(titleStyle)
.setFixedHeight(20);
TextFieldBuilder<String> subtitleBuilder = DynamicReports.cmp
.text("Start Time: " + startDate + " " + getStartTime() + ", End Time: " + endDate + " " + getEndTime())
.setFixedHeight(20);
TextFieldBuilder<String> noDataMsgBuilder = DynamicReports.cmp
.text(NO_DATA_MSG)
.setStyle(columnStyle);
builder
.title(titleBuilder)
.addPageHeader(subtitleBuilder)
.setColumnTitleStyle(columnTitleStyle)
.columns(col1, col2, col3, col4, col5, col6, col7, col8, col9)
.setColumnStyle(columnStyle)
.highlightDetailOddRows()
.noData(titleBuilder, subtitleBuilder, noDataMsgBuilder)
.setWhenNoDataType(WhenNoDataType.NO_DATA_SECTION);
String reportHtml;
try {
// this seems to be required to get to the DynamicReports images
getContext().getRequest().getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, builder.toJasperPrint());
builder.toHtml(htmlExporter);
reportHtml = writer.toString();
}
catch (DRException e)
{
e.printStackTrace();
reportHtml = "There was an error generating the report";
}

Edit: Below solution works fine only with DynamicJasper library rather than DynamicReports. There must be similar operations in DR API as well i believe (not sure though - my exposure with DR is only very limitted :().
A combination of DynamicReportBuilder::setHeaderHeight(..), setDetailHeight(..) and JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN parameter setting must do it?
// build dynamicreport instance
DynamicReportBuilder dynamicReportBuilder = new DynamicReportBuilder();
dynamicReportBuilder.setHeaderHeight(50); //sets the column header height
dynamicReportBuilder.setDetailHeight(50); //sets the detail band rows height
DynamicReport dynamicReport = dynamicReportBuilder.build();
// build jasperprint..
JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(
dynamicReport, new ClassicLayoutManager(), dataSource, new HashMap<String, Object>());
// export as html
JRExporter exporter = new JRHtmlExporter();
// tell jasper not to use images for aligning
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, targetFile);
exporter.exportReport();

adapt reports band heigts to heigth of your row for each band, make sure that you dont have any emty spaces between your rows. If you want to have "emty row" create an emty text field with width of the corresponding band. Think about the report as about grid.

Related

Select specific range/scope of a pivot table to apply format on (Aspose.Cells for Java)

Is there an equivalent of this VBA function PivotTable.PivotSelect in Aspose.Cells product ?
I am looking for a way to create a border on a whole selection of cells containing specific data field values, or on a specific scope as you prefer.
The VBA macro to perform this action is the following, by giving only the data field name parameter :
v_wbx.Sheets(v_SheetName).**PivotTables(v_CurrentPivotName).PivotSelect **DataFieldName**, xlDataAndLabel, True**
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Color = v_Color
.TintAndShade = 0
.Weight = v_Weight
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Color = v_Color
.TintAndShade = 0
.Weight = v_Weight
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Color = v_Color
.TintAndShade = 0
.Weight = v_Weight
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Color = v_Color
.TintAndShade = 0
.Weight = v_Weight
End With
Is this covered by Aspose.Cells ? I looked into documentation but haven't found any solution.
I'm aware that the "scope" selection is available with the Aspose conditional formatting, but here I want to create the border around the WHOLE selection of cells by specifying the data field name, and NOT use any Conditional Format rule.
This is done via VBA using this enum : https://learn.microsoft.com/en-us/office/vba/api/excel.xlptselectionmode and the function mentioned before.
I precise I'm using the trial version of the product to evaluate the range of features.
Please share your positive or negative feedback on this topic, thank you
You can format specific data area values in the Pivot Table via Aspose.Cells for Java. See the following example for your reference. You can apply formatting via both ways (i.e., use directly apply formatting and via pivot format condition).
e.g.
Sample code:
//Instantiating a Workbook object
Workbook workbook = new Workbook();
//Obtaining the reference of the newly added worksheet
int sheetIndex = workbook.getWorksheets().add();
Worksheet sheet = workbook.getWorksheets().get(sheetIndex);
Cells cells = sheet.getCells();
//Setting the value to the cells
Cell cell = cells.get("A1");
cell.setValue("Sport");
cell = cells.get("B1");
cell.setValue("Quarter");
cell = cells.get("C1");
cell.setValue("Sales");
cell = cells.get("A2");
cell.setValue("Golf");
cell = cells.get("A3");
cell.setValue("Golf");
cell = cells.get("A4");
cell.setValue("Tennis");
cell = cells.get("A5");
cell.setValue("Tennis");
cell = cells.get("A6");
cell.setValue("Tennis");
cell = cells.get("A7");
cell.setValue("Tennis");
cell = cells.get("A8");
cell.setValue("Golf");
cell = cells.get("B2");
cell.setValue("Qtr3");
cell = cells.get("B3");
cell.setValue("Qtr4");
cell = cells.get("B4");
cell.setValue("Qtr3");
cell = cells.get("B5");
cell.setValue("Qtr4");
cell = cells.get("B6");
cell.setValue("Qtr3");
cell = cells.get("B7");
cell.setValue("Qtr4");
cell = cells.get("B8");
cell.setValue("Qtr3");
cell = cells.get("C2");
cell.setValue(1500);
cell = cells.get("C3");
cell.setValue(2000);
cell = cells.get("C4");
cell.setValue(600);
cell = cells.get("C5");
cell.setValue(1500);
cell = cells.get("C6");
cell.setValue(4070);
cell = cells.get("C7");
cell.setValue(5000);
cell = cells.get("C8");
cell.setValue(6430);
PivotTableCollection pivotTables = sheet.getPivotTables();
//Adding a PivotTable to the worksheet
int index = pivotTables.add("=A1:C8", "E3", "PivotTable2");
//Accessing the instance of the newly added PivotTable
PivotTable pivotTable = pivotTables.get(index);
//Unshowing grand totals for rows.
pivotTable.setRowGrand(false);
//Dragging the first field to the row area.
pivotTable.addFieldToArea(PivotFieldType.ROW, 0);
//Dragging the second field to the column area.
pivotTable.addFieldToArea(PivotFieldType.COLUMN, 1);
//Dragging the third field to the data area.
pivotTable.addFieldToArea(PivotFieldType.DATA, 2);
pivotTable.refreshData();
pivotTable.calculateData();
/*
//Apply formatting to specific data area values via Pivot format condition.
PivotFormatConditionCollection pfcc = pivotTable.getPivotFormatConditions();
int pIndex = pfcc.add();
PivotFormatCondition pfc = pfcc.get(pIndex);
FormatConditionCollection fcc = pfc.getFormatConditions();
CellArea dataBodyRange = pivotTable.getDataBodyRange();
fcc.addArea(dataBodyRange);
int idx = fcc.addCondition(FormatConditionType.CELL_VALUE);
FormatCondition fc = fcc.get(idx);
fc.setFormula1("6000");
fc.setOperator(OperatorType.GREATER_OR_EQUAL);
//fc.getStyle().setBackgroundColor(com.aspose.cells.Color.getRed());
fc.getStyle().setBorder(BorderType.LEFT_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
fc.getStyle().setBorder(BorderType.TOP_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
fc.getStyle().setBorder(BorderType.RIGHT_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
fc.getStyle().setBorder(BorderType.BOTTOM_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
*/
///*
//Apply formatting directly to specific data fields.
CellArea dataArea = pivotTable.getDataBodyRange();
for(int dataRowNum = dataArea.StartRow; dataRowNum <= dataArea.EndRow;dataRowNum++){
for(int dataColNum = dataArea.StartColumn;dataColNum <= dataArea.EndColumn;dataColNum++){
cell = cells.get(dataRowNum,dataColNum);
int value = cell.getIntValue();
System.out.println(value);
if (value > 6000) {
Style style = cell.getStyle();
com.aspose.cells.Font font = style.getFont();
font.setColor(com.aspose.cells.Color.getBlue());
style.setBorder(BorderType.LEFT_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
style.setBorder(BorderType.TOP_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
style.setBorder(BorderType.RIGHT_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
style.setBorder(BorderType.BOTTOM_BORDER, CellBorderType.THICK, com.aspose.cells.Color.getRed());
pivotTable.format(dataRowNum, dataColNum, style);
}
}
}
workbook.save("f:\\files\\out1.xlsx");
You may also post your queries in the dedicated forum.
PS. I am working as Support developer/ Evangelist at Aspose.

Splitting rows of Nested Table OR Inner Table using iTextPDF

How do I split the rows of the inner table. Problem description according to the image.
Here, I have table named PARENT_TABLE that has cell that contains two tables named HEADER_TABLE and CONTENT_TABLE
CONTENT_TABLE has a cell that contains INNER_TABLE. INNER_TABLE contains the dynamic rows/content whose height will be changed according to content.
So, If I make this table using one page it's working perfectly. But incase if I need to split the table in different pages it shows the error like image_2. Please help me out. As a result: The table should look like in the image_1 even if the page split into two or more pages.
Please checkout mentioned image to be more clear.
image_1
Attempt to read from field 'float com.itextpdf.text.pdf.ColumnText.maxY' on a null object reference
image_2
I just found out the solution. The issue occurs only in the case when trying to split the PDFPTable into two pages. I had used tableCell.setRowspan(2), so when trying to split the table above issue occurs.
SOLVED IT: I just made an empty cell in place of using tableCell.setRowspan(2).
private PdfPTable contentWithDateTitleAndDescription(String stringData1, String stringData2, String stringData3, String stringData4) throws IOException, BadElementException {
float relativeWidth[] = {2, 7};
PdfPTable table = new PdfPTable(relativeWidth);
table.setWidthPercentage(100);
PdfPCell cellA = new PdfPCell();
cellA.setBorder(Rectangle.NO_BORDER);
// dateCell.setRowspan(2);
cellA.setPaddingLeft(15);
cellA.setVerticalAlignment(Element.ALIGN_CENTER);
cellA.setPaddingTop(7);
Paragraph dateParagraph = new Paragraph(stringData1);
cellA.addElement(dateParagraph);
PdfPCell emptyCellB = new PdfPCell();
emptyCellB.setBorder(Rectangle.NO_BORDER);
PdfPCell cellC = new PdfPCell();
cellC.setBorder(Rectangle.NO_BORDER);
cellC.setVerticalAlignment(Element.ALIGN_LEFT);
Paragraph titleParagraph = new Paragraph(stringData2 + " / " + stringData3);
cellC.addElement(titleParagraph);
PdfPCell cellD = new PdfPCell();
cellD.setBorder(Rectangle.NO_BORDER);
cellD.setVerticalAlignment(Element.ALIGN_LEFT);
Paragraph descriptionParagraph = new Paragraph(stringData4);
cellD.addElement(descriptionParagraph);
cellD.setPaddingBottom(15);
table.addCell(cellA);
table.addCell(cellC);
table.addCell(emptyCellB);
table.addCell(cellD);
return table;
}

How to edit jasper file?

I am editing .jasper file using report tool. I am changing the alignment for parameter left to centre then i save that file. it generates the "jrxml" file also. in my Java code I can pass the .jasper location to print some items. but my changes not affect and the old design remains same..
Help me , How can I edit and save .jasper???
public static JasperPrint createRefundPrint(Ticket ticket, HashMap map) throws Exception {
final String FILE_RECEIPT_REPORT = "/com/floreantpos/report/template/RefundReceipt.jasper";
TicketDataSource dataSource = new TicketDataSource(ticket);
return createJasperPrint(FILE_RECEIPT_REPORT, map, new JRTableModelDataSource(dataSource));
}
if you use a IReport for editing your .jrxml reports, you should just press the "Preview" button. Then the .jasper report file will be generated automatically in folder that contains the .jrxml file
To edit jasper report, you make your changes in the JRXML file. Once you build or compile your report it will generate a .jasper file which is used in your java code.
you try make dynamic report.
You do not have a location problem when you generate your own report.
Example;
public JasperDesign createDesign() throws JRException {
JasperDesign jasperDesign = new JasperDesign();
jasperDesign.setName("sampleDynamicJasperDesign");
jasperDesign.setPageWidth(595); // page width
jasperDesign.setPageHeight(842); // page height
jasperDesign.setColumnWidth(515); // column width of page
jasperDesign.setColumnSpacing(0);
jasperDesign.setLeftMargin(40);
jasperDesign.setRightMargin(40);
jasperDesign.setTopMargin(20);
jasperDesign.setBottomMargin(20);
JRDesignExpression expression = new JRDesignExpression();
//Set style of page.
JRDesignStyle normalStyle = new JRDesignStyle();
normalStyle.setName("Sans_Normal");
normalStyle.setDefault(true);
normalStyle.setFontName("DejaVu Sans");
normalStyle.setFontSize(12);
normalStyle.setPdfFontName("Helvetica");
normalStyle.setPdfEncoding("Cp1252");
normalStyle.setPdfEmbedded(false);
jasperDesign.addStyle(normalStyle);
/*
* Generate field dynamically
* */
JRDesignField field = new JRDesignField();
field.setName("firstName");
field.setValueClass(String.class);
jasperDesign.addField(field);
field = new JRDesignField();
field.setName("lastName"); // set name for field.
field.setValueClass(String.class); // set class for field. Its always depends upon data type which we want to get in this field.
jasperDesign.addField(field); // Added field in design.
field = new JRDesignField();
field.setName("age");
field.setValueClass(Integer.class);
jasperDesign.addField(field);
JRDesignBand band = new JRDesignBand();
//Title Band
band = new JRDesignBand();
band.setHeight(30);
JRDesignStaticText staticText = new JRDesignStaticText();
staticText.setText("Person's Specification");
staticText.setX(0);
staticText.setY(0);
staticText.setHeight(20);
staticText.setWidth(515);
staticText.setHorizontalAlignment(HorizontalAlignEnum.CENTER);
band.addElement(staticText);
jasperDesign.setTitle(band);
band = new JRDesignBand(); // New band
band.setHeight(20); // Set band height
/*Create text field dynamically*/
JRDesignTextField textField = new JRDesignTextField();
textField.setX(0); // x position of text field.
textField.setY(0); // y position of text field.
textField.setWidth(160); // set width of text field.
textField.setHeight(20); // set height of text field.
JRDesignExpression jrExpression = new JRDesignExpression(); // new instanse of expression. We need create new instance always when need to set expression.
jrExpression.setText(""" + "First Name: " + """ + "+" + "$F{firstName}"); // Added String before field in expression.
textField.setExpression(jrExpression); // set expression value in textfield.
band.addElement(textField); // Added element in textfield.
textField = new JRDesignTextField();
textField.setX(160);
textField.setY(0);
textField.setWidth(160);
textField.setHeight(20);
jrExpression = new JRDesignExpression();
jrExpression.setText("$F{lastName}" + "+" + """ + " :Last Name" + """); // Added string after field value
textField.setExpression(jrExpression);
band.addElement(textField);
textField = new JRDesignTextField();
textField.setX(320);
textField.setY(0);
textField.setWidth(160);
textField.setHeight(20);
jrExpression = new JRDesignExpression();
String age = """ + "<font>" + """ + "+" + """ + "Age is: " + """ + "+" + """ + "</font><font>" + """ + "+" + "$F{age}" + "+" + """ + "</font>" + """; // added html in text field with different color.
jrExpression.setText(age);
textField.setExpression(jrExpression);
textField.setMarkup("html"); // By Default markup is none, We need to set it as html if we set expression as html.
band.addElement(textField);
((JRDesignSection) jasperDesign.getDetailSection()).addBand(band);
return jasperDesign;
}
You can compile a .jrxml in Project Explorer window of Jaspersoft Studio. For that first find your .jrxml report and rightclick on it. In context menu choose 'Compile report'. Then you get compiled .jasper report.

Displaying Image in JTable

I'm trying to display an Image into column No 25 of a JTable :- For that i wrote the below code :-
jTable1.getColumnModel().getColumn(25).setCellRenderer(jTable1.getDefaultRenderer(ImageIcon.class));
String query = "SELECT name,type,supplier, department, manufacturer, model, serial_no, description, location, broker, dop, installation_date, expiring_date, retiring_date,warranty_info, icost, rcost, aarea, voltage, wattage, amperage, eline, capacity, plink, notes, adding_date, modification_date from assets where company_code='" + ims.MainWindow.cc + "' and adding_date between '" + new java.sql.Date(df.parse(df.format(jXDatePicker1.getDate())).getTime()) + "' and '" + new java.sql.Date(df.parse(df.format(jXDatePicker2.getDate())).getTime()) + "'";
System.out.println(query);
ResultSet rs = st.executeQuery(query);
int xx = 1;
byte[] imagedata=null;
ImageIcon format=null;
java.awt.Image originalImage=null;
java.awt.Image scaledImage=null;
javax.swing.ImageIcon newIconImage=null;
while (rs.next()) {
if(rs.getBytes(24)!=null){
imagedata=rs.getBytes(24);
format = new ImageIcon(imagedata);
originalImage = format.getImage();
scaledImage = originalImage.getScaledInstance(268, 200, java.awt.Image.SCALE_SMOOTH);
newIconImage = new javax.swing.ImageIcon(scaledImage);
}
mod.addRow(new Object[]{xx, rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getString(11), rs.getString(12), rs.getString(13), rs.getString(14), rs.getString(15), rs.getString(16), rs.getString(17), rs.getString(18), rs.getString(19), rs.getString(20), rs.getString(21), rs.getString(22), rs.getString(23), newIconImage, rs.getString(25), rs.getString(26), rs.getString(27)});
xx++;
}
When i run the frame containing the below code ,instead of showing an Icon in the Image column "javax.swing.ImageIcon#119537a" is being shown in the image column . Pls help
You can try changing the column number where you set the image icon renderer.
I.e try 24 in
jTable1.getColumnModel().getColumn(25).setCellRenderer(jTable1.getDefaultRenderer(ImageIcon.class));
I suspect the renderer is not changed for the column where you added the image icon.
When i run the frame containing the below code ,instead of showing an
Icon in the Image column "javax.swing.ImageIcon#119537a" is being
shown in the image column .
I think that have to set proper ColumnClass for Icon/ImageIcons (in this case and only)
JTable knows Icon/ImageIcons data type in the ColumnClass, same as String, Number, Boolean and e.i.
I think you need to change the column number to 24 instead of 25.
jTable1.getColumnModel().getColumn(24).setCellRenderer(jTable1.getDefaultRenderer(ImageIcon.class));

How to collate multiple jrxml jasper reports into a one single pdf output file

I have to prepare reports using five different sql queries. Each query will give out one report table.
So I wrote 5 jrxml files each corresponding to one of the above query with their own headings, title settings, footers, pagenumbers, etc.
Now, I am able to compile, print and export each of the above jrxmls into 5 different pdfs.
However, client wants all the reports collated into one single pdf. That is in the final pdf, first four pages will be say report one, next five pages report two, then report three and so on and so forth.
1) How to achieve this ?
2) Each report has page number as 1/4, 2/4, 3/4 etc. Where the second part i.e. the complete page number is evaluated with evaluation time as report. So when I will collate all reports in single pdf (if possible), will it also be possible to re-number the pages in justification to final pdf ?
Based on the answer below, I did the following in my java class and it works:
try
{
JasperReport jreport1 = JasperCompileManager.compileReport(input1);
JasperPrint jprint1 = JasperFillManager.fillReport(jreport1, new HashMap(), new JREmptyDataSource());
//JasperExportManager.exportReportToPdfFile(jprint, "/home/ashutosh/Desktop/desktop/nikunj/JasperTestApp/output/mytest.pdf");
JasperReport jreport2 = JasperCompileManager.compileReport(input2);
JasperPrint jprint2 = JasperFillManager.fillReport(jreport2, new HashMap(), new JREmptyDataSource());
JasperReport jreport3 = JasperCompileManager.compileReport(input3);
JasperPrint jprint3 = JasperFillManager.fillReport(jreport3, new HashMap(), new JREmptyDataSource());
List<JasperPrint> jprintlist = new ArrayList<JasperPrint>();
jprintlist.add(jprint1);
jprintlist.add(jprint2);
jprintlist.add(jprint3);
JRExporter exporter = new JRPdfExporter();
exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT_LIST, jprintlist);
OutputStream output = new FileOutputStream(new File("/home/ashutosh/Desktop/desktop/nikunj/JasperTestApp/output/mytestbatch.pdf"));
exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM, output);
exporter.exportReport();
}catch(Exception e)
{
e.printStackTrace();
}
Above: input1, input2, input3 are string paths to input jrxmls
Where my JRXML files just print three messages: Hello World 1, Hello World 2, Hello World 3.
<?xml version="1.0"?>
<!DOCTYPE jasperReport
PUBLIC "-//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="Simple_Report">
<detail>
<band height="20">
<staticText>
<reportElement x="180" y="0" width="200" height="20"/>
<text><![CDATA[Hello World One!]]></text>
</staticText>
</band>
</detail>
</jasperReport>
Thanks for reading!
You can take advantage of exporting the whole jasperprint list:
List jpList = new ArrayList();
jpList.add(JRLoader.loadObjectFromFile("build/reports/Report1.jrprint"));
...
JRExporter exporter = new JRPdfExporter();
exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT_LIST, jpList);
exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM, stream);
exporter.exportReport();
This answer is to help users with JASPER REPORT VERSION >5.6 (latest
versions), hence remove the deprecated code.
Since jasper-report 5.6 JRPdfExporterParameter.JASPER_PRINT_LIST is deprecated the current code of Wojtek Owczarczyk answer is:
List<JasperPrint> jpList = new ArrayList<>();
//add your JasperPrint's from loading jrprint or more
//commonly filling report with JasperFillManager.fillReport
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(SimpleExporterInput.getInstance(jpList)); //Set as export input
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(stream)); //Set output stream
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
//set your configuration
exporter.setConfiguration(configuration);
exporter.exportReport();
Page numbers without itext...
private void drawPageNumbers(List<JasperPrint> listJasperPrint, int totalPages) throws JRException {
int pageCount = 0;
int posY = 0;
int posX = 0;
for (JasperPrint jasperPrint : listJasperPrint) {
if (jasperPrint.getOrientation() == JRReport.ORIENTATION_PORTRAIT) {
posY = 805;
posX = 472;
}
if (jasperPrint.getOrientation() == JRReport.ORIENTATION_LANDSCAPE) {
posY = 558;
posX = 717;
}
for (Object obj : jasperPrint.getPages()) {
pageCount++;
JRPrintPage page = (JRPrintPage) obj;
JRPrintText textTotalPages = new JRTemplatePrintText(new JRTemplateText(
jasperPrint.getOrigins()[0], jasperPrint.getDefaultStyleProvider()));
textTotalPages.setX(posX + 54);
textTotalPages.setY(posY);
textTotalPages.setWidth(40);
textTotalPages.setHeight(16);
textTotalPages.setText(" " + totalPages);
page.addElement(textTotalPages);
JRPrintText textPageNumber = new JRTemplatePrintText(new JRTemplateText(
jasperPrint.getOrigins()[0], jasperPrint.getDefaultStyleProvider()));
textPageNumber.setX(posX);
textPageNumber.setY(posY);
textPageNumber.setWidth(80);
textPageNumber.setHeight(16);
textPageNumber.setText("Página " + pageCount + " de");
page.addElement(textPageNumber);
}
}
return;
}
you can try this one
JasperPrint jp1 = JasperFillManager.fillReport(reportFile1,reportParams,Connection);
JasperPrint jp2 = JasperFillManager.fillReport(reportFile2,reportParams,Connection);
for (int j = 0; j < jp1.getPages().size(); j++) {
//Add First report to second report
jp2.addPage((JRPrintPage) jp1.getPages().get(j));
}
(iReport example)
Part I:
create a new blank jasper report as a wrapper report for different reports
data adapter = One empty record - Empty Rows
click "New..."
choose "empty rows"
click "next"
number of empty records = 1 (so you will simulate on record and only ONE detail band will be printed)
so the blank report is ready
When you call this report out of your JAVA program, first open a data connection to the database and exchange this connection in the background. SubReports of our wrapper report can inherit this connection via parameters!
Part 2)
add for every report you want to embed a new detail band.
each detail band contains a subreport (link to the other standalone report of course)
set the property "run to bottom" to "True" in the subreport definition of our wrapper report
this concept works for me.
depending on parameters, you can switch different bands on or off, of course.

Categories