Hot questions for Using JasperReports in subreport

Question:

I am creating a report in Jasper with four parts. Each part consists of a text field as the header and a subreport. The subreport can be empty. If it is empty it is hidden using Remove Line When Blank. This works so far. Now, the corresponding header text field should be hidden too if the subreport is hidden.

I have tried many things but couldn't come up with a solution. E.g. using Print When Expression: new Boolean ($P{otherField}.read() != -1). This never showed the header.

As well I tried to hide the header in my Java program but couldn't find an appropriate API command. I guess getBands()[x].getChildren()[y] lead me to the right header but I couldn't hide it there.

Any other ideas?


Answer:

You should put the header text inside the subreport in for example a title band

In subreport

<title>
    <band height="38">
        <textField>
            <reportElement x="10" y="0" width="100" height="20" uuid="4b8ece47-1608-4d08-bc0b-e6b73bcf8346"/>
            <textFieldExpression><![CDATA["TITLE"]]></textFieldExpression>
        </textField>
    </band>
</title>

Make sure you do not have the attribute whenNoDataType on jasperReport tag, so it uses default value NoPages

If the subreport has no records the attribute whenNoDataType=NoPages (default) will ensure that nothing is returned and you will not see the title.

If you need it outside of subreport (for some strange reason) pass record count from subreport back to main report and use a text field with printWhenExpression and evalutationTime="Report"

Check out this for some additional details on how to pass back report count.

How to get report_count from subreport in iReport

Question:

There's a main report file containing subreports. It is compiled to .jasper and I access it by loading it into JaserReport class.

I am able to get fields and datasets trough

report.getMainDataset().getFields();

However I am unable to get subreports, I've been trying to get them trough the

report.getAllBands();

and then using the for clause

 for (int i = 0; i < bands.length; i++) {
            JRElement[] element = bands[i].getElements(); 
  }

This way I can get some JRBaseSubreport classes, and it is as far as I can get. I can access the elements of subreports, but can't get the names of subreports.

Is there any way to do that?


Answer:

You can not get data in subreport by only loading the main report into JasperReport object. This object only contains the main report and it's elements.

The element relative to the subreport is a JRBaseSubreport, which has reference to data relative to subreport tag in main report, hence it does not contain the actual report object.

The subreport will be loaded by the filler depending on the expressions, you could actually load a different sub report depending on the values of your datasource so jasper report can't know what sub report to load until the report is filled.

But you can access the expression it will use to load the subreport and this maybe can be enough in your case

Example on how to access the expression (subreport in first detail band)

//I know the subreport is in first detail band so I access this directly 
JRBaseBand detailBand1 = (JRBaseBand) report.getDetailSection().getBands()[0];
List<JRChild> elements = detailBand1.getChildren(); //Get all children
for (JRChild child : elements) {
    if (child instanceof JRBaseSubreport){ //This is a subreport
        JRBaseSubreport subreport = (JRBaseSubreport)child;
        String expression= ""; //Lets find out the expression used
        JRExpressionChunk[] chunks = subreport.getExpression().getChunks();
        for (JRExpressionChunk c : chunks) {
            expression +=c.getText();
        }
        System.out.println(expression); 
        //Here you could do code to load the subreport into a JasperReport object
    }
}

With this data you can load the subreport manually into another JasperReport object and access name, fields etc. Naturally if you have a complex expression your code will need to reflect this (retrive parameters or data from datasource)

Question:

I made a jasper report that includes a subreport using JasperSoft Studio. When i preview it in the studio, it works fine. But when i add it into my java fx project, i have to send the subreport as a parameter to the main report right?

When i do that i keep on getting an error saying that the subreport resource not found. I dont think there is any spelling errors because i hv tried this with almost all the reports that includes subreports.. still keep on getting that error..

These are the things i tried 1. compiled the report again using the jaspersoft studio and includeded them again in the project.. 2. included the jrxml file into the project and compiled it with the Compile Manager.. 3. i read some tutorials and questions saying that to put the expression to the subreport element in the main report as

$P{SUBREPORT_DIR} + "subreport_2.jasper"

but i still keep on getting the same error and i dont know what i am doing wrong Below is my code

method in application used to view the report

@FXML
    public void btnMarkingSchemeClicked(ActionEvent actionEvent) {
        try {

//            JasperReport compiledReport = (JasperReport) JRLoader.loadObject(ViewAssignmentsController.class.getResourceAsStream("/edu/ijse/gdse41/ams/reports/MarkingScheme.jasper"));
            JasperReport compiledReport = JasperCompileManager.compileReport(ViewAssignmentsController.class.getResourceAsStream("/edu/ijse/gdse41/ams/reports/MarkingScheme.jrxml"));
            HashMap<String, Object> parameters = new HashMap<>();
            parameters.put("assignID", aid);
            parameters.put("course", cmbCourse.getSelectionModel().getSelectedItem().toString());
            parameters.put("subject", cmbSub.getSelectionModel().getSelectedItem().toString());
            parameters.put("semester", cmbSem.getSelectionModel().getSelectedItem().toString());
            parameters.put("assign", ctrlAssign.search(aid).getAssignName());
//            JasperReport subReport = (JasperReport) JRLoader.loadObject(ViewAssignmentsController.class.getResourceAsStream("/edu/ijse/gdse41/ams/reports/Answers.jasper"));
            JasperReport subReport = JasperCompileManager.compileReport(ViewAssignmentsController.class.getResourceAsStream("/edu/ijse/gdse41/ams/reports/Answers.jrxml"));
            parameters.put("subReport", subReport);
            JasperPrint fillReport = JasperFillManager.fillReport(compiledReport, parameters, ConnectionFactory.getInstance().getConnection());
            JasperViewer.viewReport(fillReport, false);

        } catch (JRException | SQLException | ClassNotFoundException ex) {
            Logger.getLogger(ViewAssignmentsController.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

my main report source -- MarkingScheme.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.3.1.final using JasperReports Library version 6.3.1  -->
<!-- 2017-06-02T12:52:20 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="MarkingScheme" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="c71b946b-2ba2-4208-97f8-f32e8bcf3fb4">
    <property name="com.jaspersoft.studio.data.sql.tables" value=""/>
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="amsAdapter"/>
    <parameter name="course" class="java.lang.String"/>
    <parameter name="subject" class="java.lang.String"/>
    <parameter name="semester" class="java.lang.String"/>
    <parameter name="assign" class="java.lang.String"/>
    <parameter name="assignID" class="java.lang.String">
        <defaultValueExpression><![CDATA[$P{assignID}]]></defaultValueExpression>
    </parameter>
    <parameter name="subReport" class="net.sf.jasperreports.engine.JasperReport">
        <parameterDescription><![CDATA[]]></parameterDescription>
        <defaultValueExpression><![CDATA[$P{subReport}]]></defaultValueExpression>
    </parameter>
    <queryString language="SQL">
        <![CDATA[SELECT ams.question.qid,
    ams.question.question,
    ams.assign_ques.aid
FROM ams.assign_ques
    INNER JOIN ams.question ON 
     ams.assign_ques.qid = ams.question.qid and ams.assign_ques.aid=$P{assignID}]]>
    </queryString>
    <field name="qid" class="java.lang.String"/>
    <field name="question" class="java.lang.String"/>
    <field name="aid" class="java.lang.String"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="79" splitType="Stretch">
            <staticText>
                <reportElement mode="Opaque" x="0" y="0" width="555" height="79" forecolor="#FFFFFF" backcolor="#113891" uuid="52ed193a-ed11-46ba-a09f-1864b843df96"/>
                <textElement textAlignment="Left" verticalAlignment="Middle">
                    <font size="29" isBold="true"/>
                </textElement>
                <text><![CDATA[   Marking Scheme]]></text>
            </staticText>
        </band>
    </title>
    <pageHeader>
        <band height="80" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="80" height="40" uuid="55b35bb0-5ea8-4417-88be-0083cfee5037"/>
                <textElement textAlignment="Left" verticalAlignment="Middle">
                    <font size="14"/>
                </textElement>
                <text><![CDATA[Course]]></text>
            </staticText>
            <staticText>
                <reportElement x="0" y="40" width="80" height="40" uuid="1dc04c2d-9cde-4905-9650-03cc96d406e3"/>
                <textElement textAlignment="Left" verticalAlignment="Middle">
                    <font size="14"/>
                </textElement>
                <text><![CDATA[Semester]]></text>
            </staticText>
            <staticText>
                <reportElement x="260" y="0" width="100" height="40" uuid="4de2dbe2-bb88-4dbf-88d7-16b36bba8fb4"/>
                <textElement textAlignment="Left" verticalAlignment="Middle">
                    <font size="14"/>
                </textElement>
                <text><![CDATA[Subject]]></text>
            </staticText>
            <staticText>
                <reportElement x="260" y="40" width="100" height="40" uuid="bb91c5d3-4cde-45eb-8083-012fe6183396"/>
                <textElement textAlignment="Left" verticalAlignment="Middle">
                    <font size="14"/>
                </textElement>
                <text><![CDATA[Assignment]]></text>
            </staticText>
            <textField>
                <reportElement x="90" y="0" width="160" height="40" forecolor="#123278" uuid="8016c655-1bea-480a-9179-3da4e1e930ad"/>
                <textElement verticalAlignment="Middle">
                    <font size="13"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{course}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="370" y="0" width="170" height="40" forecolor="#123278" uuid="23e58b4b-0bf1-41ae-89f0-48808a0abdd9"/>
                <textElement verticalAlignment="Middle">
                    <font size="13"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{subject}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="90" y="40" width="160" height="40" forecolor="#123278" uuid="650c412a-0c42-4dea-a96f-35d03c11c926"/>
                <textElement verticalAlignment="Middle">
                    <font size="13"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{semester}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="370" y="40" width="170" height="40" forecolor="#123278" uuid="c8cbea5b-afb3-4c85-a96a-156d1c82fb50"/>
                <textElement verticalAlignment="Middle">
                    <font size="13"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{assign}]]></textFieldExpression>
            </textField>
        </band>
    </pageHeader>
    <columnHeader>
        <band height="30" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="100" height="30" uuid="f7b84a13-8e80-4c9c-8888-3b081f9d0f55"/>
                <textElement>
                    <font size="16" isBold="true"/>
                </textElement>
                <text><![CDATA[Questions]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="41" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="80" height="20" uuid="9f05a7d2-ac5f-4412-b26b-ab37033cc0fe"/>
                <textElement verticalAlignment="Middle">
                    <font size="12"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{qid}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="100" y="0" width="440" height="20" uuid="a299bfe0-a0d1-4aae-8f75-5b58d24b1760"/>
                <textElement verticalAlignment="Middle">
                    <font size="12"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{question}]]></textFieldExpression>
            </textField>
            <subreport>
                <reportElement x="100" y="20" width="440" height="20" uuid="72f8c7c2-82ca-48d3-bb89-d5bb4846e1bc"/>
                <subreportParameter name="qid">
                    <subreportParameterExpression><![CDATA[$F{qid}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA["Answers.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </detail>
</jasperReport>

my sub report source -- Answers.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.3.1.final using JasperReports Library version 6.3.1  -->
<!-- 2017-06-02T12:53:52 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Answers" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="142adbc1-da50-458b-b076-ba8aa716124f">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="amsAdapter"/>
    <property name="com.jaspersoft.studio.data.sql.tables" value="YW1zLmFuc3dlciAsMTUsMTUsOGE1MjQ1NzQtOGY1ZS00ZWY4LWFiMDAtOWVjYmVmNmU0MTFjOw=="/>
    <parameter name="qid" class="java.lang.String">
        <defaultValueExpression><![CDATA[$P{qid}]]></defaultValueExpression>
    </parameter>
    <queryString>
        <![CDATA[SELECT ams.answer.answer_id,
    ams.answer.answer,
    ams.answer.correctness,
    ams.answer.qid
FROM ams.answer where ams.answer.qid=$P{qid} and ams.answer.correctness=1]]>
    </queryString>
    <field name="answer_id" class="java.lang.String"/>
    <field name="answer" class="java.lang.String"/>
    <field name="correctness" class="java.lang.Boolean"/>
    <field name="qid" class="java.lang.String"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <detail>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="80" height="20" uuid="517ba9e8-6637-4808-8517-1485d4125971"/>
                <textElement>
                    <font size="12"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{answer_id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="90" y="0" width="460" height="20" uuid="4384510c-5dea-47a0-b24b-d4b3bd4088fc"/>
                <textElement>
                    <font size="12"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{answer}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

the error im getting

net.sf.jasperreports.engine.JRException: Resource not found at: Answers.jasper. at net.sf.jasperreports.repo.RepositoryUtil.getResourceFromLocation(RepositoryUtil.java:153) at net.sf.jasperreports.repo.RepositoryUtil.getReport(RepositoryUtil.java:112) at net.sf.jasperreports.engine.fill.JRFillSubreport.loadReport(JRFillSubreport.java:398) at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateReport(JRFillSubreport.java:365) at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluateSubreport(JRFillSubreport.java:427) at net.sf.jasperreports.engine.fill.JRFillSubreport.evaluate(JRFillSubreport.java:341) at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:381) at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:500) at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2022) at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:748) at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:255) at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:115) at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:582) at net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:396) at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:90) at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:456) at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:863) at edu.ijse.gdse41.ams.view.controller.ViewAssignmentsController.btnMarkingSchemeClicked(ViewAssignmentsController.java:174) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71) at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275) at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769) at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Node.fireEvent(Node.java:8413) at javafx.scene.control.Button.fire(Button.java:185) at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89) at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Scene$MouseHandler.process(Scene.java:3757) at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485) at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762) at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494) at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381) at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417) at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389) at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416) at com.sun.glass.ui.View.handleMouseEvent(View.java:555) at com.sun.glass.ui.View.notifyMouse(View.java:937) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191) at java.lang.Thread.run(Thread.java:745)


Answer:

It is because even though you have created a parameter called "subReport" it hasn't been used anywhere.

           <subreport>
            <reportElement x="100" y="20" width="440" height="20" uuid="72f8c7c2-82ca-48d3-bb89-d5bb4846e1bc"/>
            <subreportParameter name="qid">
                <subreportParameterExpression><![CDATA[$F{qid}]]></subreportParameterExpression>
            </subreportParameter>
            <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
            <subreportExpression><![CDATA["Answers.jasper"]]></subreportExpression>
        </subreport>

See? It is still "Answers.jasper" there in the main report. That is why it works fine in Jasper Studio. Let's change it to,

           <subreport>
            <reportElement x="100" y="20" width="440" height="20" uuid="72f8c7c2-82ca-48d3-bb89-d5bb4846e1bc"/>
            <subreportParameter name="qid">
                <subreportParameterExpression><![CDATA[$F{qid}]]></subreportParameterExpression>
            </subreportParameter>
            <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
            <subreportExpression><![CDATA[$P{subReport}]]></subreportExpression>
        </subreport>

I am pretty sure that I am not the one who taught you to use Jasper :) Let's hope it will work

Question:

I built a report template; which uses a base report for headers and footers, and then a subreport into which a report can be injected. In general this works fine; however I have noted that there are blank pages after the subreport has finished generating in the master report.

It occurs to me that this is simply caused by the fact that the master report template and the subreport are not on the same page when it comes to pagination; for example the subreport I am testing uses its own datasource and has grouping.

Is there a way to cut off the extraneous pages? My master report template has the following property set (to no avail):

When No Data Type: No Pages

The subreport has the same setting.

I found one helpful post here: JasperReports: How to remove new page blank in subreport

This suggested adding the following parameter to the reportElement tag for the actual subreport:

isRemoveLineWhenBlank="true"

Doing this actually removed all but one extra blank page; which is a huge success. But still, one blank page left.

This is what the source looked like after the change:

<subreport overflowType="Stretch">
    <reportElement x="-20" y="0" width="792" height="20" isRemoveLineWhenBlank="true" uuid="e6d4ec67-6ce6-4bbb-b40b-edfb1cfb4722">

Due to the general nature of the problem; especially when articulating the question in the title, I am finding it hard to find relevant articles on the subject. If there are any relevant pages/blog posts/articles, the info would be most appreciated.


Answer:

If you generate reports with Java you can delete last empty page as workaround.

JasperPrint jp = JasperFillManager.fillReport(report, params, dataSource);
for (Iterator<JRPrintPage> iterator = jp.getPages().iterator(); iterator.hasNext();) {
     JRPrintPage page = iterator.next();
     if (!iterator.hasNext() && page.getElements().isEmpty()) {
          iterator.remove();
     }
 }

Question:

I'm trying to implement table of contents in my Jasper report. Here is an example offered on Jasper Reports site of how to do it: https://sourceforge.net/p/jasperreports/code/ci/jr-6-2-1/tree/jasperreports/demo/samples/tableofcontents/reports/

In the example above they run a query against a db to obtain data to fill the report part*. In my case I need to fill the report part with data obtained from JavaBean and I can't find a solution to it.

I figured out how to pass a datasource from a wrapping report to a report part as a parameter but I don't know how to use it there so that all report part fields are mapped to it. Regularly (without report parts) as far as I know it is done automatically.

What I have done so far:

  1. Java code to create the report:
JasperCompileManager.compileReportToFile("TablePart.jrxml", "TablePart.jasper");
JasperReport jasperReport = JasperCompileManager.compileReport("TableOfContentsReport.jrxml");
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(generateBeanList());
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<>(), dataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "TableOfContentsReport.pdf");
  1. Java bean
public class MyBean {

    private Integer orderId;
    private String shipName;
    private String shipCity;
    private String shipCountry;
    private Integer total;

    public Integer getOrderId() {
        return orderId;
    }

    public void setOrderID(Integer orderId) {
        this.orderId = orderId;
    }

    public String getShipName() {
        return shipName;
    }

    public void setShipName(String shipName) {
        this.shipName = shipName;
    }

    public String getShipCity() {
        return shipCity;
    }

    public void setShipCity(String shipCity) {
        this.shipCity = shipCity;
    }

    public String getShipCountry() {
        return shipCountry;
    }

    public void setShipCountry(String shipCountry) {
        this.shipCountry = shipCountry;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }
}
  1. Wrapping report jrxml template (slightly modified version of TableOfContentsReport.jrxml (link above)):
<jasperReport ... sectionType="Part" ...>
    <group name="dummy">
        <groupExpression><![CDATA[]]></groupExpression>
        <groupHeader>
        ...
            <part>
                <p:subreportPart xmlns:p="http://jasperreports.sourceforge.net/jasperreports/parts"                            xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/parts http://jasperreports.sourceforge.net/xsd/parts.xsd"
                                 usingCache="true">
                    <subreportParameter name="REPORT_DATA_SOURCE">
                        <subreportParameterExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></subreportParameterExpression>
                    </subreportParameter>
                    <subreportExpression><![CDATA["TablePart.jasper"]]></subreportExpression>
                </p:subreportPart>
            </part>
        </groupHeader>
    </group>
</jasperReport>

I found it is possible to pass the datasource from the wrapping report to the report part as a parameter: $P{REPORT_DATA_SOURCE}

But how can I use it in the report part to map corresponding fields (Jasper Reports fields to JavaBean fields)? The way it is now all the declared fields in the report part evaluate to null.

  1. Report part (slightly modified version of TablePart.jrxml (link above))
<jasperReport ...>
    <queryString><![CDATA[]]></queryString>
    <field name="orderId" class="java.lang.Integer"/>
    <field name="shipName" class="java.lang.String"/>
    <field name="shipCity" class="java.lang.String"/>
    <field name="shipCountry" class="java.lang.String"/>
    ...
</jasperReport>

These are the fields (orderId, shipName, etc) I need to be set with the corresponding values of the passed JavaBean.

*Just in case, here is a reference on the report parts subject: http://jasperreports.sourceforge.net/sample.reference/book/index.html


Answer:

The problem is that the datasource you are passing to the subreport is already consumed.

The JRDatasource uses next to iterate the detail band in main report and when it is passed to subreport its at the end.

Solution:

  1. Pass to main report a new JREmptyDataSource(1), only 1 record is needed

  2. Pass your datasource as parameter in the HashMap<String,Object> es map.put("subreportDataSource",dataSource)

  3. Pass to subreport this datasource

    <subreportParameter name="REPORT_DATA_SOURCE">
       <subreportParameterExpression><![CDATA[$P{subreportDataSource}]]></subreportParameterExpression>
    </subreportParameter>
    

Follow up question

is it possible to kind of share one datasource between all report parts?

Not directly as datasource but in your case you could pass the generateBeanList() as a parameter map.put("dsList",generateBeanList()) and then to each subreport pass new JRBeanCollectionDataSource($P{dsList})

Question:

I have deep nested Set of strings in my model and I can't list them in my jasper report.

My model:

Profile:
List<Project> projectList;

    Project:
    Skill skills;

          Skill:
          Set<String> programmingLanguages;

I create report where Profile is main report, Skill is subreport but I can't get data from programmingLanguages Set in Skill subreport.

My jrxml files:

Profile report

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="jasper-test" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="9f3515b2-a9bf-4194-ae0f-ceb8d4de1e70">
<parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false"/>
  <field name="projectList" class="java.util.List"/>
<detail>
<band height="299" splitType="Stretch">
<subreport>
                <reportElement x="-2" y="148" width="555" height="51" uuid="f081f980-ea14-4434-9282-beebf515cb6c"/>
                <subreportParameter name="SUBREPORT_DIR"/>
                <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource
                    ($F{projectList})]]></dataSourceExpression>
                <subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "jasper-subreport-project.jasper"]]></subreportExpression>
</subreport>
</band> 

</detail>
</jasperReport>

Project subreport:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="jasper-test" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="9f3515b2-a9bf-4194-ae0f-ceb8d4de1e70">
<field name="skills" class="com.company.profilelist.model.Skill"/>
<detail>
<band height="299" splitType="Stretch">
    <subreport>
                <reportElement x="296" y="43" width="200" height="100" uuid="1084d612-8188-4dcc-8b09-6e534e76b879"/>
                <subreportParameter name="skills">
                    <subreportParameterExpression><![CDATA[$F{skills}]]></subreportParameterExpression>
                </subreportParameter>
                 <subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "jasper-subreport-skills.jasper"]]></subreportExpression>
            </subreport>
</band> 

</detail>
</jasperReport>

Skill subreport:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="jasper-test" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="9f3515b2-a9bf-4194-ae0f-ceb8d4de1e70">
<field name="programmingLanguages" class="java.util.Set">
<detail>
<band height="299" splitType="Stretch">
    <textField>
                <reportElement x="100" y="20" width="119" height="23" uuid="085d4a07-8dfa-4de4-b89d-6d915681fbc5"/>
                <textElement>
                    <font size="9"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{programmingLanguages}]]></textFieldExpression>
            </textField>
</band> 

</detail>
</jasperReport>

I can't reach programmingLanguage field in skills subreport is there something I'm missing ?


Answer:

try with following steps,

firstly, declare the skills as a List in the project model

Project:
List<Skill> skills;

then, change the class of field skills to java.util.List in the project report

<field name="skills" class="java.util.List"/>

finally, add dataSourceExpression for skill sub report in the project report and remove the subreportParameterExpression of skill sub report in the project report

<subreport>
    <reportElement x="296" y="43" width="200" height="100" uuid="1084d612-8188-4dcc-8b09-6e534e76b879"/>
    <subreportParameter name="skills"/>
    <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{skills})]]></dataSourceExpression>                
    <subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "jasper-subreport-skills.jasper"]]></subreportExpression>
</subreport>

Question:

My JasperReports's report has subreport. Using the ByteArrayInputStream parameter into the main report and main report query result have more than one row Could not generate pdf. But the main report query result set has an only one result set PDF to generate without any error

My Java code for passing subreport:

Map<String, Object> parameters = new HashMap<String, Object>(); 
parameters.put("subreportParameter", subreportinputstream)

Declaration of parameter at jrxml:

<parameter name="subreportParameter" class="java.io.ByteArrayInputStream"/>

This is how I'm calling subreport:

 <subreport>
   <reportElement positionType="Float" x="275" y="55" width="240" height="70" uuid="0010fc8e-593e-45ee-af10-952fd8b54ad5" />
   <subreportParameter name="reportid">
      <subreportParameterExpression><![CDATA[$P{reportid}]]></subreportParameterExpression>
   </subreportParameter>
   <subreportParameter name="currencycode">
      <subreportParameterExpression><![CDATA[$P{currencycode}]]></subreportParameterExpression>
   </subreportParameter>
   <subreportParameter name="taxcode">
      <subreportParameterExpression><![CDATA[$P{taxcode}]]></subreportParameterExpression>
   </subreportParameter>
   <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
   <subreportExpression class="net.sf.jasperreports.engine.JasperReport"><![CDATA[$P{subreportParameter}]]></subreportExpression>
</subreport>

Answer:

When the subreport renders the second time, it tries to load the report from the $P{subreportParameter} input stream, but that stream has already been read the first time the subreport rendered so reading from it again will not produce any data.

The simplest way to fix this is to set the isUsingCache flag for the subreport:

<subreport isUsingCache="true">
    ...

Alternatively, you can load the JasperReport object yourself from the stream by doing JRLoader.loadObject(subreportinputstream) and pass the JasperReport object as report parameter instead of the stream.

Question:

I'm having serious problems trying to figure out how to pass parameters to sub-subreports in jasperreports from java code.

The hierarchy I'm talking about looks like the following:

mainReport

--------------> subReport

---------------------------> subSubReport

So far, I tried to pass the parameters needed in the subSubReport to the mainReport and from there pass it to the subReport and from there to the subSubReport but this it's not working. In fact, I do get a pdf file with the contents of the mainReport and the subReport but the content of the subSubReport is not displaying. That's why I'm guessing my problem is that I shouldn't be passing the parameters (SUBREPORT_DIR more specifically) of the subSubReport to the mainReport but to the subReport and that's what I don't know how to achieve. Also, there is little (and incomplete) information on the web about it.

Can someone please help me?

mainReport code

<subreport>
                <reportElement key="" x="0" y="0" width="554" height="30" isRemoveLineWhenBlank="true" uuid="18ff5513-835d-4910-b39c-6d41252b4679"/>
                <subreportParameter name="REPORT_CONNECTION">
                    <subreportParameterExpression><![CDATA[$P{REPORT_CONNECTION}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="REPORT_DATA_SOURCE">
                    <subreportParameterExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="SUBREPORT_DIR">
                    <subreportParameterExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="SUBREPORT1LEVEL1">
                    <subreportParameterExpression><![CDATA[$P{SUBREPORT1LEVEL1}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA[$P{SUBREPORT1LEVEL1}]]></subreportExpression>
</subreport>

subReport code

<subreport>
                <reportElement x="50" y="10" width="457" height="40" uuid="4528914e-bb9a-4300-8173-14be2ff2db85"/>
                <subreportParameter name="REPORT_CONNECTION">
                    <subreportParameterExpression><![CDATA[$P{REPORT_CONNECTION}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="REPORT_DATA_SOURCE">
                    <subreportParameterExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="SUBREPORT_DIR">
                    <subreportParameterExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="SUBREPORT1LEVEL2">
                    <subreportParameterExpression><![CDATA[$P{SUBREPORT1LEVEL2}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA[$P{SUBREPORT1LEVEL2}]]></subreportExpression>
            </subreport>

Answer:

Currently you are setting each report level with a parameter equalling itself, rather than passing it down.

What you need to do is pass the parameter from the level above for each level of sub-report e.g. if you have a parameter at the top level, you need to pass this to the sub-level via the associated sub-report parameter, and then pass this level's parameter to the sub-sub-report i.e. the next level down.

For instance, let's assume we want to pass a Boolean server check parameter from the top level to the bottom, with the parameters "IsOnserver", "IsOnserverL1" and "IsOnserverL2" for each respective report level. At the main report level we would have this:

<parameter name="IsOnServer" class="java.lang.Boolean">
    <defaultValueExpression><![CDATA[true]]></defaultValueExpression>
</parameter>

For the next level (the sub-report) we would do the following, to fill this with the main report parameter's value:

<parameter name="IsOnServerL1" class="java.lang.Boolean">
    <defaultValueExpression><![CDATA[$P{IsOnServer}]]></defaultValueExpression>
</parameter>

For your 3rd and final level parameter (the sub-sub-report) we would pass the sub-report parameter value:

<parameter name="IsOnServerL2" class="java.lang.Boolean">
    <defaultValueExpression><![CDATA[$P{IsOnServerL1}]]</defaultValueExpression>
</parameter>

This will result in the main report parameter being passed down the line correctly.

Question:

I am creating jasper pdf using java. I wan to add subreports dynamically to main report.

Main reported is created using below code :

JasperDesign jasperDesign = JRXmlLoader.load("/home/report1.jrxml");
    jasperDesign.setName("sampleDynamicJasperDesign");
    jasperDesign.setPageWidth(595);jasperDesign.setPageHeight(842);jasperDesign.setColumnWidth(595-40-40);jasperDesign.setColumnSpacing(0);
    jasperDesign.setLeftMargin(40);jasperDesign.setRightMargin(40);jasperDesign.setTopMargin(20);jasperDesign.setBottomMargin(20);

    JRDesignStyle normalStyle = new JRDesignStyle();
    normalStyle.setName("Noto Sans");normalStyle.setDefault(true); normalStyle.setFontName("Noto Sans");normalStyle.setFontSize(12);normalStyle.setPdfFontName("Helvetica");normalStyle.setPdfEncoding("Cp1252");normalStyle.setPdfEmbedded(false);jasperDesign.addStyle(normalStyle);
((JRDesignSection) jasperDesign.getDetailSection()).addBand(createHeaderSubreport(parameters));

//create subreport

    private JRBand createHeaderSubreport(Map<String, Object> parameters) throws JRException {

    JasperDesign jasperDesign = new JasperDesign(); 
    jasperDesign.setLanguage("java");
    jasperDesign.setPageWidth(595); jasperDesign.setPageHeight(842);jasperDesign.setColumnWidth(595-40-40);jasperDesign.setColumnSpacing(0);jasperDesign.setLeftMargin(40);jasperDesign.setRightMargin(40);jasperDesign.setTopMargin(20); jasperDesign.setBottomMargin(20);
    jasperDesign.setTitle(null);jasperDesign.setColumnHeader(null);

    JRDesignParameter designParameter = new JRDesignParameter(); designParameter.setName("LeftText");designParameter.setValueClass(String.class);
    jasperDesign.addParameter(designParameter);
    JRDesignStyle normalStyle = new JRDesignStyle();
    normalStyle.setName("Noto Sans");normalStyle.setDefault(true);normalStyle.setFontName("Noto Sans");normalStyle.setFontSize(12); normalStyle.setPdfFontName("Helvetica");normalStyle.setPdfEncoding("Cp1252"); normalStyle.setPdfEmbedded(false);jasperDesign.addStyle(normalStyle);

    JRDesignBand band = new JRDesignBand();
    band.setHeight(50);

    JRDesignStaticText designStaticText = new JRDesignStaticText();
    designStaticText.setText("Header");
    designStaticText.setHeight(10);
    designStaticText.setWidth(100);
    designStaticText.setX(0);designStaticText.setY(0);
    band.addElement(designStaticText);

    JRDesignTextField jrDesignTextField = new JRDesignTextField();
    JRDesignExpression jrExpression = new JRDesignExpression();
    jrExpression.setText("$P{LeftText}");
    jrDesignTextField.setExpression(jrExpression);
    jrDesignTextField.setY(0);
    jrDesignTextField.setHeight(20);
    jrDesignTextField.setWidth((38*515)/100);
    jrDesignTextField.setMarkup("html");
    jrDesignTextField.setHorizontalTextAlign(HorizontalTextAlignEnum.LEFT);
    jrDesignTextField.setStretchWithOverflow(true);
    band.addElement(jrDesignTextField);

    ((JRDesignSection) jasperDesign.getDetailSection()).addBand(band);

    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

    JRDesignSubreport jSubreport = new JRDesignSubreport(jasperDesign); 
    jSubreport.setUsingCache(false); 
    jSubreport.setRemoveLineWhenBlank(true); 
    jSubreport.setPrintRepeatedValues(false);
    jSubreport.setWidth(500);
    jSubreport.setHeight(80);
    jSubreport.setX(0);jSubreport.setY(0);

    JRDesignExpression expression = new JRDesignExpression();
    expression.setText("new net.sf.jasperreports.engine.JREmptyDataSource(1)");
    jSubreport.setDataSourceExpression(expression);        
    jSubreport.setExpression(expression);

    JRDesignSubreportParameter designSubreportParameter = new JRDesignSubreportParameter();  designSubreportParameter.setName("REPORT_CONNECTION");    
    JRDesignExpression exp = new JRDesignExpression("$P{REPORT_CONNECTION}");  designSubreportParameter.setExpression(exp);
    jSubreport.addParameter(designSubreportParameter);


    designSubreportParameter = new JRDesignSubreportParameter();  designSubreportParameter.setName("LeftText"); 
  exp = new JRDesignExpression("$P{LeftText}");  designSubreportParameter.setExpression(exp);
  jSubreport.addParameter(designSubreportParameter);

    band = new JRDesignBand();
    band.setHeight(80);
    band.addElement(jSubreport);
    return band;
}

Then after compling and filling main report, subreport is printing as blank.But individually subreport works.

Even I have tried by passing dataSourceExpression as new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{notes}) still its printing blank.

I am not getting where I am wrong, Please help


Answer:

Compile your design.

JasperReport subReport = JasperCompileManager.compileReport(subJasperDesign);

Then add it as param to your main report.

parameters.put("SUB_TEMPLATE", subReport);

Get this param in jrxml template:

<parameter name="SUB_TEMPLATE" class="net.sf.jasperreports.engine.JasperReport"/>

And finally jrxml usage example of this param:

<band height="15">
<subreport>
<reportElement x="0" y="0" width="802" height="15" />
<dataSourceExpression><![CDATA[$F{SUB_DATASOURCE_NAME}]]></dataSourceExpression>
<subreportExpression><![CDATA[$P{SUB_TEMPLATE}]]></subreportExpression>
/subreport>
</band>

Question:

I created a jasper report using iReport with 3 subreports which works perfectly in the iReport designer, but when i call the main jrxml with Java like so

JasperReport jasperReport = JasperCompileManager.compileReport("C:\\jasperFiles\\main.jrxml");
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, connect);
JasperViewer.viewReport(jasperPrint);

i get an error: (All files, main.jrxml/.jasper, and subreport files both .jrxml & .jasper are in the same directory)

ERROR MESSAGE:    
net.sf.jasperreports.engine.JRException: Resource not found at : main_personal_details.jasper

My main.jrxml(which is working perfectly in iReport)

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="main" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a7db71b8-8789-45e2-a322-24a2d664325c">
<parameter name="memberId" class="java.lang.Integer"/>
<parameter name="month" class="java.lang.String"/>
<parameter name="year" class="java.lang.String"/>
<queryString>
    <![CDATA[SELECT 1]]>
</queryString>
<field name="1" class="java.lang.Long"/>
<title>
    <band height="71" splitType="Stretch">
        <staticText>
            <reportElement uuid="68c7bfae-7a3d-441e-ae30-6d18f9b957e4" x="0" y="0" width="555" height="25"/>
            <textElement>
                <font size="18" isBold="true"/>
            </textElement>
            <text><![CDATA[Test Subreport]]></text>
        </staticText>
    </band>
</title>
<detail>
    <band height="93" splitType="Stretch">
        <staticText>
            <reportElement uuid="ca4ee210-2997-494d-a33d-1e6811941ac9" x="0" y="0" width="191" height="20"/>
            <textElement>
                <font fontName="Times New Roman" size="12" isBold="true"/>
            </textElement>
            <text><![CDATA[PERSONAL DETAILS]]></text>
        </staticText>
        <subreport>
            <reportElement uuid="f850bec8-0aee-4c6e-a57e-606db1e318ca" x="100" y="20" width="455" height="66"/>
            <subreportParameter name="memberId">
                <subreportParameterExpression><![CDATA[$P{memberId}]]></subreportParameterExpression>
            </subreportParameter>
            <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
            <subreportExpression><![CDATA["main_personal_details.jasper"]]></subreportExpression>
        </subreport>
    </band>
    <band height="131">
        <staticText>
            <reportElement uuid="b503e7a0-fb52-4985-ba75-c915d0539410" x="0" y="0" width="555" height="26" backcolor="#C0C0C0"/>
            <textElement verticalAlignment="Middle">
                <font fontName="Times New Roman" size="12" isBold="true"/>
            </textElement>
            <text><![CDATA[MILK COLLECTION DETAILS]]></text>
        </staticText>
        <subreport>
            <reportElement uuid="b8d60dc1-10da-4ef8-8ee0-04a9f1131216" x="100" y="26" width="455" height="100"/>
            <subreportParameter name="month">
                <subreportParameterExpression><![CDATA[$P{month}]]></subreportParameterExpression>
            </subreportParameter>
            <subreportParameter name="year">
                <subreportParameterExpression><![CDATA[$P{year}]]></subreportParameterExpression>
            </subreportParameter>
            <subreportParameter name="memberId">
                <subreportParameterExpression><![CDATA[$P{memberId}]]></subreportParameterExpression>
            </subreportParameter>
            <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
            <subreportExpression><![CDATA["main_subreport1.jasper"]]></subreportExpression>
        </subreport>
    </band>
    <band height="125">
        <staticText>
            <reportElement uuid="7c17a8dc-eea4-47e2-9ba8-9bcdd68f31c2" x="0" y="3" width="555" height="24" backcolor="#C0C0C0"/>
            <textElement verticalAlignment="Middle">
                <font fontName="Times New Roman" size="14" isBold="true"/>
            </textElement>
            <text><![CDATA[DEDUCTIONS]]></text>
        </staticText>
        <subreport>
            <reportElement uuid="cf920e0e-ce30-46a4-a491-c687f80940d9" x="100" y="27" width="455" height="97"/>
            <subreportParameter name="month">
                <subreportParameterExpression><![CDATA[$P{month}]]></subreportParameterExpression>
            </subreportParameter>
            <subreportParameter name="year">
                <subreportParameterExpression><![CDATA[$P{year}]]></subreportParameterExpression>
            </subreportParameter>
            <subreportParameter name="memberId">
                <subreportParameterExpression><![CDATA[$P{memberId}]]></subreportParameterExpression>
            </subreportParameter>
            <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
            <subreportExpression><![CDATA["main_deductions.jasper"]]></subreportExpression>
        </subreport>
    </band>
</detail>

Please help me to be able to call this report template in Java code and pass parameters accordingly.


Answer:

set "SUBREPORT_DIR" property under "subreport" tag in "main.jrxml" like below

 <parameter name="SUBREPORT_DIR" class="java.lang.String"
  isForPrompting="false">
  <defaultValueExpression>
  <![CDATA["C:\\tools\\jasperreports-5.0.1\\test\\"]]>
  </defaultValueExpression>

find the complete code here.

http://www.tutorialspoint.com/jasper_reports/jasper_create_subreports.htm

Question:

I have an issue displaying my sub-reports when they are inserted through java. My goal is to insert them dynamically, so I do not know which sub-reports will be used beforehand. The master page gets displayed correctly, while the subreports are blank. Seems like I'm missing a connection to the subreport. Maybe someone can see where the issue lies? Sorry for not providing a minimal working example. This is my method for setting parameters and returns JasperPrint object:

private JasperPrint createReport(String masterReportFile, String subReportFile, JasperReportFileType fileType, String reportName) throws Exception {
    JRBeanCollectionDataSource ticketsJRBean = new JRBeanCollectionDataSource(workStatList
            .stream()
            .map(this::generateNewJasperReportTicketObject)
            .collect(Collectors.toList()));
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    InputStream reportTemplate = new FileInputStream(context.getRealPath("") + JasperReportConstants.TemplateLocation.TEMPLATES_DEFAULT.getFullLocation(masterReportFile));
    Map<TemplateLocation, JasperReport> subreportMap = provideRequiredReportsMap(subReportFile, context);
    JasperReport jasperMasterReport = new JasperMasterReport(Optional.of(reportTemplate), reportName, subreportMap).createAndGetJasperReport();
    Map<String, Object> paramsMaster = new HashMap<>();
    setupMasterReportParameters(paramsMaster, fileType);
    Map<String, Object> paramsSub = new HashMap<>();
    paramsMaster.put(JasperTicketReport.PARAM_TICKET_SUBREPORT, subreportList.get(TemplateLocation.TICKETS));
    paramsMaster.put(JasperTicketReport.PARAM_TICKET_DATASOURCE, ticketsJRBean);
    paramsMaster.put(JasperTicketReport.PARAM_HEADER_ID, "HEADER");
    return JasperFillManager.fillReport(jasperMasterReport, paramsMaster);
}

And this is the class method, that creates the link to the sub-report:

@Override
public JasperReport createAndGetJasperReport() throws Exception {
    try {
        initializeReport();
        subReportMap.forEach((key, value) -> insertSubReport(key, value));
        return JasperCompileManager.compileReport(jasperDesign);
    } catch (JRException ex) {
        LOGGER.log(Level.ERROR, ex.getMessage());
        throw new Exception(ex.getMessage());
    }
}
private void insertSubReport(TemplateLocation templateLocation, JasperReport report) {
    try {
        JRDesignBand subreportBand = new JRDesignBand();
        subreportBand.setHeight(50);
        JRDesignSubreport subreport = new JRDesignSubreport(jasperDesign);
        subreport.setX(0);
        subreport.setY(0);
        subreport.setHeight(20);
        subreport.setWidth(355);
        JRDesignExpression expression = new JRDesignExpression();
        JRDesignSubreportParameter jrDesignSubreportParameterDataSource = new JRDesignSubreportParameter();
        JRDesignSubreportParameter jrDesignSubreportParameterHeaderId = new JRDesignSubreportParameter();
        if (TemplateLocation.TICKETS.equals(templateLocation)) {
            defineParameter(JRBeanCollectionDataSource.class, JasperTicketReport.PARAM_TICKET_DATASOURCE);
            defineParameter(JasperReport.class, JasperTicketReport.PARAM_TICKET_SUBREPORT);
            defineParameter(String.class, JasperTicketReport.PARAM_HEADER_ID);
            expression.setText("$P{" + JasperTicketReport.PARAM_TICKET_SUBREPORT + "}");
            subreport.setExpression(expression);
            expression = new JRDesignExpression();
            expression.setText("$P{" + JasperTicketReport.PARAM_HEADER_ID + "}");
            jrDesignSubreportParameterHeaderId.setExpression(expression);
            jrDesignSubreportParameterHeaderId.setName("ticketHeader");
            subreport.addParameter(jrDesignSubreportParameterHeaderId);
            expression = new JRDesignExpression();
            expression.setText("$P{" + JasperTicketReport.PARAM_TICKET_DATASOURCE + "}");
            jrDesignSubreportParameterDataSource.setExpression(expression);
            jrDesignSubreportParameterDataSource.setName("ticketDataSource");
            subreport.addParameter(jrDesignSubreportParameterDataSource);
        }
        subreportBand.addElement(subreport);
        ((JRDesignSection) jasperDesign.getDetailSection()).addBand(subreportBand);
    } catch (JRException ex) {
        LOGGER.log(Level.ERROR, ex.getMessage());
    }
}

This is my master jrxml file:

    <?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.11.0.final using JasperReports Library version 6.11.0-0c4056ccaa4d25a5a8c45672d2f764ea3498bebb  -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Process_A4_Landscape" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="43b18c10-7dae-49ef-ae13-0a6e88c9a593">
    <parameter name="title" class="java.lang.String"/>
    <parameter name="logoBinary" class="java.io.ByteArrayInputStream"/>
    <parameter name="filter" class="java.lang.String"/>
    <parameter name="disp" class="java.lang.String"/>
    <field name="id" class="java.lang.Integer"/>
    <field name="Title" class="java.lang.String">
        <fieldDescription><![CDATA[$P{title}]]></fieldDescription>
    </field>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="60" splitType="Stretch">
            <image>
                <reportElement x="0" y="0" width="77" height="60" uuid="651ccc4b-e999-40fe-bcbf-1f25bcfc98af"/>
                <imageExpression><![CDATA[$P{logoBinary}]]></imageExpression>
            </image>
            <textField>
                <reportElement x="251" y="0" width="300" height="60" uuid="20b118bd-4ca6-4b6a-993d-19f038c89768">
                    <property name="com.jaspersoft.studio.unit.width" value="px"/>
                </reportElement>
                <textElement textAlignment="Center">
                    <font size="18"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{title}]]></textFieldExpression>
            </textField>
        </band>
    </title>
    <pageHeader>
        <band height="77" splitType="Stretch">
            <textField>
                <reportElement x="53" y="23" width="500" height="30" uuid="ece41608-e59d-4b05-b736-d4c84c420074">
                    <property name="com.jaspersoft.studio.unit.x" value="px"/>
                    <property name="com.jaspersoft.studio.unit.width" value="px"/>
                </reportElement>
                <textElement>
                    <font size="8"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{filter}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="0" y="23" width="50" height="30" uuid="89f432c5-6e8e-4e56-9317-9131d59e4e31">
                    <property name="com.jaspersoft.studio.unit.x" value="px"/>
                    <property name="com.jaspersoft.studio.unit.width" value="px"/>
                </reportElement>
                <textElement>
                    <font size="8" isBold="true"/>
                </textElement>
                <text><![CDATA[FILTER]]></text>
            </staticText>
        </band>
    </pageHeader>
    <columnHeader>
        <band height="50"/>
    </columnHeader>
    <detail>
        <band height="280" splitType="Stretch"/>
    </detail>
    <pageFooter>
        <band height="69" splitType="Stretch">
            <textField pattern="dd/MM/yyyy HH:mm">
                <reportElement x="50" y="23" width="100" height="30" uuid="6924da96-3fd4-455a-8361-bca736aad641"/>
                <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="351" y="19" width="100" height="30" uuid="2143305d-6a29-4bc0-a689-1f359db58d49"/>
                <textFieldExpression><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression>
            </textField>
        </band>
    </pageFooter>
    <summary>
        <band height="46" splitType="Stretch"/>
    </summary>
</jasperReport>

And this is my sub-report:

 <?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.11.0.final using JasperReports Library version 6.11.0-0c4056ccaa4d25a5a8c45672d2f764ea3498bebb  -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Process_A4_Landscape" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="43b18c10-7dae-49ef-ae13-0a6e88c9a593">
    <style name="Table_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="Table_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="Table_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
            <topPen lineWidth="0.5" lineColor="#000000"/>
            <leftPen lineWidth="0.5" lineColor="#000000"/>
            <bottomPen lineWidth="0.5" lineColor="#000000"/>
            <rightPen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <subDataset name="TicketDataSet" uuid="af87285f-3ee2-454d-8102-313d6ab38914">
        <parameter name="headerId" class="java.lang.String"/>
        <parameter name="headerSubject" class="java.lang.String"/>
        <parameter name="headerProject" class="java.lang.String"/>
        <parameter name="headerType" class="java.lang.String"/>
        <parameter name="headerDuration" class="java.lang.String"/>
        <queryString>
            <![CDATA[]]>
        </queryString>
        <field name="id" class="java.lang.Integer"/>
        <field name="subject" class="java.lang.String"/>
        <field name="fileName" class="java.lang.String"/>
        <field name="typeName" class="java.lang.String"/>
        <field name="workMinutes" class="java.lang.Integer"/>
    </subDataset>
    <parameter name="headerId" class="java.lang.String"/>
    <parameter name="headerSubject" class="java.lang.String"/>
    <parameter name="headerProject" class="java.lang.String"/>
    <parameter name="headerType" class="java.lang.String"/>
    <parameter name="headerDuration" class="java.lang.String"/>
    <parameter name="ticketsDataSource" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <field name="Title" class="java.lang.String">
        <fieldDescription><![CDATA[TEST]]></fieldDescription>
    </field>
    <background>
        <band splitType="Stretch"/>
    </background>
    <columnHeader>
        <band height="62" splitType="Stretch">
            <componentElement>
                <reportElement x="170" y="0" width="410" height="62" uuid="ea0d1bc7-20ee-4a73-8e20-82494215b940">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                    <property name="com.jaspersoft.studio.table.style.table_header" value="Table_TH"/>
                    <property name="com.jaspersoft.studio.table.style.column_header" value="Table_CH"/>
                    <property name="com.jaspersoft.studio.table.style.detail" value="Table_TD"/>
                </reportElement>
                <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                    <datasetRun subDataset="TicketDataSet" uuid="061b061f-f5d5-4892-b3c4-e5b8d85f28a1">
                        <datasetParameter name="headerId">
                            <datasetParameterExpression><![CDATA[$P{headerId}]]></datasetParameterExpression>
                        </datasetParameter>
                        <dataSourceExpression><![CDATA[$P{ticketsDataSource}]]></dataSourceExpression>
                    </datasetRun>
                    <jr:column width="50" uuid="635ee962-de22-4d7e-a89f-395ad81bdb3c">
                        <property name="com.jaspersoft.studio.components.table.model.column.name" value="Column1"/>
                        <jr:tableHeader style="Table_TH" height="30" rowSpan="1">
                            <textField>
                                <reportElement x="0" y="0" width="50" height="30" uuid="c8b56f8c-593a-4c70-98bd-c20ceb88a528"/>
                                <textElement textAlignment="Left"/>
                                <textFieldExpression><![CDATA[$P{headerId}]]></textFieldExpression>
                            </textField>
                        </jr:tableHeader>
                        <jr:detailCell style="Table_TD" height="30">
                            <textField>
                                <reportElement x="0" y="0" width="50" height="30" uuid="32ef7b8c-84cb-4b59-85a9-decfdaf76967"/>
                                <textElement textAlignment="Left"/>
                                <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
        </band>
    </columnHeader>
    <detail>
        <band height="302" splitType="Stretch">
            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.spreadsheet.SpreadsheetLayout"/>
        </band>
    </detail>
    <columnFooter>
        <band height="45" splitType="Stretch"/>
    </columnFooter>
</jasperReport>

Answer:

So there were two things I needed to do, to make the sub-report appear:

  1. As suggested by data67, I needed to set up a JREmptyDataSource() on my subreport:subreport.setDataSourceExpression(new JRDesignExpression("new net.sf.jasperreports.engine.JREmptyDataSource()"));

  2. I needed to insert my subreport (after I set-up all the parameters) into the column header of the master report: ((JRDesignBand) jasperDesign.getColumnHeader()).addElement(subreport);

Question:

im new in jasper report, and im creating a java program that will export report to a pdf file, and im using jasper report with multiple subreport, im creating the jrxml files with jaspersoft studio.

this is the subreport part from my main report jrxml file

        <subreport>
            <reportElement positionType="Float" x="18" y="1" width="522" height="65" uuid="f3063ed3-775f-47df-8306-a939aecc9d89"/>
            <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
            <subreportExpression><![CDATA["ClaimHistory.jasper"]]></subreportExpression>
        </subreport>

and another one subreport part

        <subreport>
            <reportElement positionType="Float" x="18" y="2" width="522" height="65" uuid="a70d75e0-b9d0-4f52-bb84-090993c2e90b"/>
            <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
            <subreportExpression><![CDATA["ClaimDetail.jasper"]]></subreportExpression>
        </subreport>

each subreport is using JRBeanCollectionDataSource(list) for the data, this is how im export the jasper to pdf file

    String jasperFile = "E:/jasper/jasperFile.jrxml";
    FileInputStream inputStream = new FileInputStream(jasperFile);
    JasperReport jasperReport = JasperCompileManager.compileReport(inputStream);
    List<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
    JasperPrint print = JasperFillManager.fillReport(jasperReport, params, new JREmptyDataSource());
    jasperPrintList.add(print);
    JRPdfExporter exporter = new JRPdfExporter();
    exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList)); //Set as export input my list with JasperPrint s
    exporter.setExporterOutput(new SimpleOutputStreamExporterOutput("E:/output.pdf")); //or any other out streaam
    exporter.exportReport();

my current skill is only capable of making a pdf without using a subreport by using this JRBeanCollectionDataSource(list), as data source. (the data printed successfully)

can anybody tell me how to make a pdf report with multiple subreport, whats should be on my main jrxml files and in the subreport jrxml files, and also whats should be on the java code?, and how to use multiple JRBeanCollectionDataSource(list)?, the only thing i know is using Map params = new HashMap(); but how to do it ? thanks. - sorry for my bad english tho.


Answer:

firstly defined the sub report's data sources are as fields in the main report (main.jrxml)

<field name="claimHistoryDataSource" class="java.util.ArrayList">
    <fieldDescription><![CDATA[claimHistoryList}]]></fieldDescription>
</field>

<field name="claimDetailDataSource" class="java.util.ArrayList">
    <fieldDescription><![CDATA[claimDetailList}]]></fieldDescription>
</field>

claimHistoryList and claimDetailList are ArrayLists defined in the java class which used as a data source of the main report.

then pass it to the sub report with a dataSourceExpression

<subreport>
    <reportElement positionType="Float" x="18" y="1" width="522" height="65" uuid="f3063ed3-775f-47df-8306-a939aecc9d89"/>
    <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{claimHistoryDataSource})]]></dataSourceExpression>
    <subreportExpression><![CDATA["ClaimHistory.jasper"]]></subreportExpression>
</subreport>

<subreport>
    <reportElement positionType="Float" x="18" y="1" width="522" height="65" uuid="f3063ed3-775f-47df-8306-a939aecc9d89"/>
    <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{claimDetailDataSource})]]></dataSourceExpression>
    <subreportExpression><![CDATA["ClaimDetail.jasper"]]></subreportExpression>
</subreport>

Question:

I am using the DynamicReports (4.1.0) and iReport (5.6.0) to generate pdf files. I have created a subreport in iReport which has a pie chart. After I run the code via DynamicReports, the created PDF does not show this piechart. Here is the code:

HashMap<String,Object> map = new HashMap<String,Object>();

map.put("id", "157"); //Actually, this will not be used since I pass this value statically in subreport.jrxml
Object[] array =  new Object[1];
array[0] = map;
JRMapArrayDataSource ds = new JRMapArrayDataSource(array);
InputStream is = JasperTemplateDesignReport2.class.getResourceAsStream("mainreport.jrxml");

try {
    report()
    .setTemplateDesign(is)
        .setDataSource(ds)
    .show();

} catch (DRException e) {
    e.printStackTrace();
} 

subreport.jrxml:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="templatereport2_subreport3" pageWidth="555" pageHeight="802" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" isTitleNewPage="true" uuid="3dc0ebf2-660d-4d0c-af85-ccae1f01bdee">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <parameter name="id" class="java.lang.String"/>
    <queryString>
        <![CDATA[SELECT
     count(status) AS count,
     case when status=TRUE then 'Succeeded'else 'Failed'end AS status
FROM
     "dbtable" dbtable
WHERE
     id = 157
GROUP BY
     status]]>
    </queryString>
    <field name="count" class="java.lang.Long"/>
    <field name="status" class="java.lang.String"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="351" splitType="Stretch">
            <pie3DChart>
                <chart evaluationTime="Report">
                    <reportElement x="40" y="24" width="415" height="244" uuid="a43afa44-c4e5-4ad5-b06e-8922128bcdaf"/>
                    <chartTitle/>
                    <chartSubtitle/>
                    <chartLegend/>
                </chart>
                <pieDataset>
                    <keyExpression><![CDATA[$F{status}]]></keyExpression>
                    <valueExpression><![CDATA[$F{count}]]></valueExpression>
                </pieDataset>
                <pie3DPlot>
                    <plot/>
                    <itemLabel/>
                </pie3DPlot>
            </pie3DChart>
            <textField>
                <reportElement x="134" y="292" width="100" height="20" uuid="2726affe-1fef-45a1-abc8-8da8c9856e42"/>
                <textFieldExpression><![CDATA[$F{count}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="20" y="292" width="100" height="20" uuid="fa4e41c0-b4f4-443c-ab9e-3cf048a3f520"/>
                <textFieldExpression><![CDATA[$F{status}]]></textFieldExpression>
            </textField>
        </band>
    </title>
</jasperReport>

mainreport.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="templatedesign2" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="575" leftMargin="10" rightMargin="10" topMargin="10" bottomMargin="10" uuid="8c9654e9-6770-46c4-a4d0-4bdf99195b70">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="229"/>
    <parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA["D:\\DynamicReports\\src\\subreport\\"]]></defaultValueExpression>
    </parameter>
    <field name="id" class="java.lang.String"/>
    <group name="Intro">
        <groupHeader>
            <band height="203">
                <subreport isUsingCache="false">
                    <reportElement x="0" y="69" width="575" height="77" uuid="eb90e8b6-2860-4c94-ad10-3eb5031502fc"/>
                    <subreportParameter name="SUBREPORT_DIR">
                        <subreportParameterExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportParameterExpression>
                    </subreportParameter>
                    <subreportParameter name="id">
                        <subreportParameterExpression><![CDATA[$F{id}]]></subreportParameterExpression>
                    </subreportParameter>
                    <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                    <subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "templatereport2_subreport3.jasper"]]></subreportExpression>
                </subreport>
            </band>
        </groupHeader>
    </group>
    <pageFooter>
        <band height="79" splitType="Stretch"/>
    </pageFooter>
</jasperReport>

Any ideas?


Answer:

I have modified the Java code as the following, then the Pie chart started to be displayed on the created PDF:

Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/myDB", "username", "password");
HashMap<String,Object> parmsMap = new HashMap<String,Object>();
parmsMap.put("id", "157");
String sourceFileName = 
                "D://DynamicReports//src//subreport//masterreport.jasper";
JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName, parmsMap, conn);
JasperViewer.viewReport(jasperPrint, false);
conn.close();

I believe the key thing is sending the connection which worked for me.

Question:

I am using Jaspersoft studio to create reports. I am having a sub report in my Jasper main report. The problem is I am unable to make this work, because if I add the sub report into the Detail band of the main report, the sub report get generated number of times, sometimes row by row, sometimes entire sub report repeated in number of pages. I can't put this in Summery Band due to the same reason.

I am unable to put this in Column Footer Band or other footers because it displays the below error

net.sf.jasperreports.engine.JRException: net.sf.jasperreports.engine.JRRuntimeException: Subreport overflowed on a band that does not support overflow.
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.fillReport(ReportControler.java:467)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.access$18(ReportControler.java:442)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler$4.run(ReportControler.java:334)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Caused by: net.sf.jasperreports.engine.JRRuntimeException: Subreport overflowed on a band that does not support overflow.
    at net.sf.jasperreports.engine.fill.FillerSubreportParent.addPage(FillerSubreportParent.java:113)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.addPageToParent(JRBaseFiller.java:1213)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.addPage(JRVerticalFiller.java:1836)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillPageBreak(JRVerticalFiller.java:1919)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBreak(JRVerticalFiller.java:1948)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:730)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:264)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:124)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:540)
    at net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:393)
    at net.sf.jasperreports.engine.fill.JRFillSubreport.fillSubreport(JRFillSubreport.java:704)
    at net.sf.jasperreports.engine.fill.JRSubreportRunnable.run(JRSubreportRunnable.java:59)
    at net.sf.jasperreports.engine.fill.AbstractThreadSubreportRunner.run(AbstractThreadSubreportRunner.java:203)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

I am unable to put this in page header due to below error, or else it just keep on executing.

net.sf.jasperreports.engine.JRException: net.sf.jasperreports.engine.JRRuntimeException: Infinite loop creating new page due to page header overflow.
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.fillReport(ReportControler.java:467)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.access$18(ReportControler.java:442)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler$4.run(ReportControler.java:334)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Caused by: net.sf.jasperreports.engine.JRRuntimeException: Infinite loop creating new page due to page header overflow.
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillPageHeader(JRVerticalFiller.java:415)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:258)
    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:124)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:540)
    at net.sf.jasperreports.engine.fill.BaseFillHandle$ReportFill.run(BaseFillHandle.java:120)
    at java.lang.Thread.run(Unknown Source)

Below is the code of my main report

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.0.0.final using JasperReports Library version 6.0.0  -->
<!-- 2014-12-16T11:26:41 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Portfolio_View_Report" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="961f2f5f-8ed1-422c-9a1a-6b9dcdf1624f">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="xxx"/>
    <parameter name="idPortfolio" class="java.lang.Integer"/>
    <queryString>
        <![CDATA[SELECT * FROM Client]]>
    </queryString>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="119" splitType="Stretch">
            <property name="local_mesure_unitheight" value="pixel"/>
            <property name="com.jaspersoft.studio.unit.height" value="px"/>
            <image>
                <reportElement x="210" y="1" width="140" height="76" uuid="f5d606fc-24d8-4536-9c35-56ce81c863c2"/>
                <imageExpression><![CDATA["C:/Users/xxx/JaspersoftWorkspace/xxx/xxx.png"]]></imageExpression>
            </image>
            <staticText>
                <reportElement x="0" y="80" width="210" height="30" uuid="8c8eb2f8-9d3d-46a0-9d4c-0d049e8c544d"/>
                <textElement>
                    <font fontName="Times New Roman" size="14" isBold="true" isUnderline="true"/>
                </textElement>
                <text><![CDATA[Portfolio View Report]]></text>
            </staticText>
        </band>
    </title>
    <pageHeader>
        <band height="159" splitType="Stretch">
            <staticText>
                <reportElement x="-1" y="0" width="163" height="20" uuid="8ffdf975-7965-4402-b9af-ef7785872f24"/>
                <textElement verticalAlignment="Middle">
                    <font fontName="Times New Roman"/>
                </textElement>
                <text><![CDATA[Generated By: xxx]]></text>
            </staticText>
            <textField pattern="dd-MM-yyyy">
                <reportElement x="450" y="0" width="100" height="20" uuid="cfd44de8-bc3d-4a2d-9f53-b9fdb969b061"/>
                <textElement verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
            </textField>
            <subreport runToBottom="true">
                <reportElement stretchType="RelativeToTallestObject" x="0" y="55" width="555" height="60" uuid="a99b1643-200b-4d7c-ade2-26e30b4fcc82">
                    <property name="local_mesure_unitheight" value="pixel"/>
                    <property name="com.jaspersoft.studio.unit.height" value="px"/>
                </reportElement>
                <subreportParameter name="idPortfolio">
                    <subreportParameterExpression><![CDATA[$P{idPortfolio}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA["Transactions_Report.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </pageHeader>
    <detail>
        <band height="36" splitType="Stretch">
            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.FreeLayout"/>
        </band>
    </detail>
    <columnFooter>
        <band height="285" splitType="Stretch">
            <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.FreeLayout"/>
        </band>
    </columnFooter>
    <pageFooter>
        <band height="120" splitType="Stretch"/>
    </pageFooter>
    <summary>
        <band height="100" splitType="Stretch"/>
    </summary>
</jasperReport>

Below is the code of my sub report

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.0.0.final using JasperReports Library version 6.0.0  -->
<!-- 2014-12-16T11:28:26 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Transactions_Report" pageWidth="500" pageHeight="842" columnWidth="500" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="4204d16c-e22f-46a2-b4c5-8be93fa35bc4">
    <property name="com.jaspersoft.studio.unit." value="pixel"/>
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="xxx"/>
    <parameter name="idPortfolio" class="java.lang.Integer"/>
    <queryString language="SQL">
        <![CDATA[SELECT Transactions.`idTransactions`,
Transactions.`Transaction_TimeStamp`,
Transactions.`idPortfolio`,
CASE when Transactions.`Transaction_Amount` <= 0 
     THEN NULL 
     else Transaction_Amount
END AS Encashments,
CASE when Transactions.`Transaction_Amount` > 0 
     THEN NULL 
     else (Transactions.`Transaction_Amount`*-1)
END AS Additions,
Portfolio.Activation 
FROM Transactions 
INNER JOIN Portfolio ON Transactions.idPortfolio = Portfolio.idPortfolio 
WHERE Transactions.idPortfolio= $P{idPortfolio} 
ORDER BY `Transaction_TimeStamp` DESC]]>
    </queryString>
    <field name="Transaction_TimeStamp" class="java.sql.Date">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="Additions" class="java.lang.Double"/>
    <field name="Encashments" class="java.lang.Double"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="47" splitType="Stretch">
            <staticText>
                <reportElement x="5" y="10" width="180" height="30" uuid="30e059fd-caed-4e67-a4f6-d06f2897ac59"/>
                <textElement>
                    <font fontName="Times New Roman" size="14" isBold="true" isUnderline="true"/>
                </textElement>
                <text><![CDATA[Transations]]></text>
            </staticText>
        </band>
    </title>
    <columnHeader>
        <band height="44" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="160" height="30" uuid="344e0833-c92a-47bf-bece-162b5ac7e52b">
                    <property name="local_mesure_unitwidth" value="pixel"/>
                    <property name="com.jaspersoft.studio.unit.width" value="px"/>
                </reportElement>
                <text><![CDATA[Date]]></text>
            </staticText>
            <staticText>
                <reportElement x="166" y="0" width="160" height="30" uuid="9bf82277-53b7-4244-aae9-84cf310e6d94">
                    <property name="com.jaspersoft.studio.unit.width" value="px"/>
                </reportElement>
                <text><![CDATA[Additions]]></text>
            </staticText>
            <rectangle>
                <reportElement x="0" y="30" width="490" height="1" uuid="45244617-f10e-4867-bc84-71aa0c42649b"/>
                <graphicElement>
                    <pen lineWidth="0.5"/>
                </graphicElement>
            </rectangle>
            <staticText>
                <reportElement x="330" y="0" width="160" height="30" uuid="68c554b4-0d79-4236-9e3f-db1b5dd19f7f">
                    <property name="com.jaspersoft.studio.unit.width" value="px"/>
                </reportElement>
                <text><![CDATA[Encashments]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="40" splitType="Stretch">
            <textField pattern="dd-MM-yyyy">
                <reportElement x="2" y="10" width="158" height="30" uuid="e2ab3765-dd44-4f8d-aedb-d411cce30384">
                    <property name="local_mesure_unitwidth" value="pixel"/>
                    <property name="com.jaspersoft.studio.unit.width" value="px"/>
                </reportElement>
                <textFieldExpression><![CDATA[$F{Transaction_TimeStamp}]]></textFieldExpression>
            </textField>
            <textField isBlankWhenNull="true">
                <reportElement x="166" y="10" width="160" height="30" uuid="bb3baa95-bf15-4462-bb59-3461b1f4e1c7">
                    <property name="com.jaspersoft.studio.unit.width" value="px"/>
                </reportElement>
                <textFieldExpression><![CDATA[$F{Additions}]]></textFieldExpression>
            </textField>
            <textField isBlankWhenNull="true">
                <reportElement x="330" y="10" width="160" height="30" uuid="c625f008-1390-4245-8035-9bdc98c21d79">
                    <property name="com.jaspersoft.studio.unit.width" value="px"/>
                </reportElement>
                <textFieldExpression><![CDATA[$F{Encashments}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

What is wrong with this?


Answer:

I found out that for my situation, it is best to use Tables instead of subreports. This is what I did.

  1. Create tables in Detail Band.
  2. Create and assign separate data sets to these Tables.
  3. Now, eventhough I don't need a query for the main report, I must provide one in order the jasper to continue. The query is tricky and problamatic, because if it returned more than one result, the items in the Detail Band will repeat. So, since I need the tables in the Detail Band to be printed only "once", I must restrict the result returned by the main report's query only to one. I did something like below.

    SELECT Name FROM Client WHERE idClient=1

  4. Now the items in the detail band will act only once. Since the tables in the detail band contains their own queries, the entire table will be filled with the expected results.

The same method may work for sub reports as well.

Question:

Could anyone give a simple example to call a jasper report with subreport inside subreport from a java program. Something like this (Generate Jasper report with subreport from java):

JasperReport jasperMasterReport = JasperCompileManager.compileReport(masterReportSource);
JasperReport jasperSubReport1 = JasperCompileManager.compileReport(subReportSource1);
JasperReport jasperSubReport2 = JasperCompileManager.compileReport(subReportSource2);

Map<String, Object> parameters2 = new HashMap()<String, Object>;
parameters2.put("subreportParameter2", jasperSubReport2);

Map<String, Object> parameters1 = new HashMap()<String, Object>;
parameters1.put("subreportParameter1", JasperFillManager.fillReportToFile(jasperSubReport1, parameters2, connection));

JasperFillManager.fillReportToFile(jasperMasterReport, parameters1, connection);

MasterReport.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.3.1.final using JasperReports Library version 6.3.1  -->
<!-- 2017-05-02T10:06:38 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="MasterReport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="5adfa1b1-651c-478e-a83b-6230d66dc454">
	<property name="com.jaspersoft.studio.data.sql.tables" value=""/>
	<property name="com.jaspersoft.studio.data.defaultdataadapter" value="OracleJDBC"/>
    <parameter name="subreportParameter1" class="net.sf.jasperreports.engine.JasperReport"/>
	<queryString language="SQL">
		<![CDATA[SELECT "PERSON"."ID",
	"PERSON"."FIRST_NAME",
	"PERSON"."LAST_NAME"
FROM "PERSON"]]>
	</queryString>
	<field name="ID" class="java.math.BigDecimal"/>
	<field name="FIRST_NAME" class="java.lang.String"/>
	<field name="LAST_NAME" class="java.lang.String"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<columnHeader>
		<band height="16" splitType="Stretch">
			<staticText>
				<reportElement x="0" y="0" width="93" height="16" uuid="cde3f82c-d51e-43ef-a56e-fee3cb853b65"/>
				<textElement>
					<font isBold="true"/>
				</textElement>
				<text><![CDATA[PERSONS:]]></text>
			</staticText>
		</band>
	</columnHeader>
	<detail>
		<band height="80" splitType="Stretch">
			<textField>
				<reportElement x="0" y="20" width="30" height="20" uuid="9fbab9bb-55ec-44c0-badb-501a00334fe6"/>
				<textFieldExpression><![CDATA[$F{ID}]]></textFieldExpression>
			</textField>
			<staticText>
				<reportElement x="0" y="0" width="30" height="20" uuid="3c5afed0-442f-41de-9929-abdb8a218981"/>
				<text><![CDATA[ID]]></text>
			</staticText>
			<textField>
				<reportElement x="30" y="20" width="100" height="20" uuid="2561523d-322d-487d-89a2-be44804979ee"/>
				<textFieldExpression><![CDATA[$F{FIRST_NAME}]]></textFieldExpression>
			</textField>
			<staticText>
				<reportElement x="30" y="0" width="100" height="20" uuid="431ac382-603e-47a1-b4df-b9d744041718"/>
				<text><![CDATA[FIRST NAME]]></text>
			</staticText>
			<textField>
				<reportElement x="130" y="20" width="100" height="20" uuid="9b482687-49c6-49f7-b322-ba868e4ce748"/>
				<textFieldExpression><![CDATA[$F{LAST_NAME}]]></textFieldExpression>
			</textField>
			<staticText>
				<reportElement x="130" y="0" width="100" height="20" uuid="4532e6f3-58c0-4c24-aebc-a135309d94ba"/>
				<text><![CDATA[LAST NAME]]></text>
			</staticText>
			<subreport>
				<reportElement x="2" y="40" width="550" height="40" uuid="18ecc4c5-81a1-4ae3-b3f7-3bf10c627be8"/>
				<subreportParameter name="PERSON_ID">
					<subreportParameterExpression><![CDATA[$F{ID}]]></subreportParameterExpression>
				</subreportParameter>
				<connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
				<subreportExpression><![CDATA[$P{subreportParameter1}]]></subreportExpression>
			</subreport>
		</band>
	</detail>
</jasperReport>

Answer:

You can pass the subreport path as main report parameter and get number of subreports like this.

            String file = /pathToMainReport/name.jrxml;
            String subreport1 = /pathToSubReport/name1.jasper;
            String subreport2 = /pathToSubReport/name2.jasper;      

            JasperReport jreport = JasperCompileManager.compileReport(file);


            Map<String, Object> map = new HashMap<String, Object>();

            map.put("SUBREPORT_DIR1", subreport1);
            map.put("SUBREPORT_DIR2", subreport2);

            JasperPrint jprint = JasperFillManager.fillReport(jreport, map, connection);

Question:

I am using Jasper-Reports 5.2.0 and have a main Report containing 2 sub-reports.

I have a Model ReportData which contains two attributes: List<Feld> felder and List<Wert> werte. The two sub-models contain multiple attributes with data to be displayed in a table.

So this is how I pass my Datasource to the sub-reports.

<subreport>
        <reportElement x="0" y="28" width="553" height="51" uuid="502d9559-e6bf-49c8-a34c-ffb8916634cd"/>
        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F(werte)]]></dataSourceExpression>
        <subreportExpression><![CDATA["werte_subreport.jasper"]]></subreportExpression>
</subreport>

<subreport>
        <reportElement x="0" y="90" width="555" height="50" uuid="5e5b0287-5002-4e31-aa8f-afe36ea78827"/>
        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F(felder))]]></dataSourceExpression>
        <subreportExpression><![CDATA["felder_subreport.jasper"]]></subreportExpression>
</subreport>

and this is how I fill my report (datasource is the Collection of ReportData):

printable = JasperFillManager.fillReport(PropertyLoader.getSingleton().loadAsInputStream(REPORT_FOLDER + File.separatorChar + KONFIG_JASPER),parameters, datasource);

Somehow my values are not passed to the sub-reports and Jasper Reports is trying to use attributes as defaultWert, which isn't part of the Class Wert and should be displayed in the sub-report.

net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : defaultWert
Caused by: java.lang.NoSuchMethodException: Unknown property 'defaultWert' on class XXXXXXXXXXXXXXXXXXXXXX.model.ReportData'

I defined the two Lists werte and felder as fields of type java.util.List in the Main Report and defined the attributes as for defaultWert as fields of type String in the sub-reports. What am I doing wrong?


Answer:

Thanks for your replies, I just found the problem... it was a stupid syntax mistake... it has to be $F{felder} instead of $F(felder) in my JRExpression... it ist working fine now!

Question:

I need to show a complex report that takes data from beans.

I've created a container bean, that has got the List of other beans.

public class OreComputateContainerBean implements Serializable{
    private static final long serialVersionUID = 1L;    
    private Long id; 

    private List<ViewOreGiorniMeseTotBean> listViewOreGiorniMeseTotBean;
    private List<ViewOreComputateMeseBean> listViewOreComputateMeseBean;
    private List<ViewOreComputateBean> listViewOreComputateBean;
}

In the main report on Tibco Jaspersoft, I add subreports and I create a field like

<field name="listViewOreGiorniMeseTotBean" class="java.util.List"/>

the subreport is built as follows:

<subreport>
    <reportElement x="280" y="0" width="171" height="83" uuid="a0bfc3a5-e452-4f3e-a875-2eaaf7f367e6"/>
        <subreportExpression><![CDATA[$F{listViewOreGiorniMeseTotBean}]]></subreportExpression>
</subreport>

When I try to build the report in my application, I see the following exception

net.sf.jasperreports.engine.JRRuntimeException: Unsupported subreport section type java.util.ArrayList

How do I need to build the subreport to have data shown correctly?


Answer:

There are two issues with your subreport definition:

  1. subreportExpression should define the path to subreport .jasper file
  2. data reference should be passed as dataSourceExpression. Moreover JasperReport require subreport data source to be instance of JRDataSource.

So one of the possible solutions is to modify subreport declaration to something similar to

<subreport>
    <reportElement x="280" y="0" width="171" height="83" uuid="a0bfc3a5-e452-4f3e-a875-2eaaf7f367e6"/>
    <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{listViewOreGiorniMeseTotBean})]]></dataSourceExpression>
    <subreportExpression><![CDATA[subreport_path_relative_to_SUBREPORT_DIR_variable.jasper"]]></subreportExpression>
</subreport>

Question:

I try to fill report with multi result set. But it's not working. Pleaase, give me some solution or fix my code.

ResultSet results1 = statement.executeQuery("FETCH ALL ret1;");
ResultSet results2 = statement.executeQuery("FETCH ALL ret2;");
JRResultSetDataSource ret1 = new JRResultSetDataSource(results1);
JRResultSetDataSource ret2 = new JRResultSetDataSource(results2);  
JasperPrint print;                                         
print = JasperFillManager.fillReport(report, params, ret1);

Answer:

Probably for this purpose you will need to create your own implementation of net.sf.jasperreports.engine.JRDataSource, that will be initialized with multiple data sources, in your case two.