I'm using Jasper Reports to build a simple report pdf. I have a JSON file that looks like this:
{"employees": [
{"firstName" : "John", "lastName" : "Doe"},
{"firstName" : "Anna", "lastName" : "Smith"},
{"firstName" : "Peter", "lastName" : "Jones"}
]}
And I'm trying to read it in like this:
File file = new File("E:/Workspaces/jasperPDFreport/src/main/resources/emp.json");
JsonDataSource datasource = new JsonDataSource(file);
JasperDesign jasperDesign = JRXmlLoader.load("E:/Workspaces/jasperPDFreport/src/main/resources/jsonTemplate.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
Map parameters = new HashMap();
JasperPrint jasperPrint;
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, datasource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "BasicReport.pdf");
JasperViewer.viewReport(jasperPrint);
However my the values from the JSON file are not passed to my pdf.
This is my Template:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.1.1.final using JasperReports Library version 6.1.1 -->
<!-- 2015-10-22T13:45:32 -->
<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="Blank_A4_2" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="9e494ebe-c1fb-4448-bcee-38994e9720f7">
<!--property name="net.sf.jasperreports.json.source" value="emp.json"/-->
<queryString language="json">
<![CDATA[employees]]>
</queryString>
<field name="firstName" class="java.lang.String">
<fieldDescription><![CDATA[firstName]]></fieldDescription>
</field>
<field name="lastName" class="java.lang.String">
<fieldDescription><![CDATA[lastName]]></fieldDescription>
</field>
<background>
<band splitType="Stretch"/>
</background>
<detail>
<band height="125" splitType="Stretch">
<textField>
<reportElement x="100" y="0" width="100" height="30" uuid="02b279da-3795-4655-8571-5a36a3ef378c"/>
<textFieldExpression><![CDATA[$F{firstName}]]></textFieldExpression>
</textField>
<staticText>
<reportElement x="0" y="0" width="100" height="30" uuid="671e61ad-8d8f-48cb-969f-78c05a516398"/>
<text><![CDATA[firstName]]></text>
</staticText>
<textField>
<reportElement x="100" y="30" width="100" height="30" uuid="9d53f46f-a252-48b3-9213-8c3092c29f49"/>
<textFieldExpression><![CDATA[$F{lastName}]]></textFieldExpression>
</textField>
<staticText>
<reportElement x="0" y="30" width="100" height="30" uuid="3b49affb-685a-4df2-a872-c0e6fdcab94b"/>
<text><![CDATA[lastName]]></text>
</staticText>
</band>
</detail>
</jasperReport>
Now you see the commented out line
property name="net.sf.jasperreports.json.source" value="emp.json"
If I comment this in, everything works as intended, I don't want to hard code my JSON values into the template, because later on I want to get them from a rest service, that's not ready yet. I do not understand, why the values are not getting parsed into the report, instead i just get two null values.
From JasperReports - JSON Data Source Sample (version 6.4.3)
The built-in JSON query executer (see the JsonQueryExecuter class) is a tool that uses the query string to produce a JsonDataSource instance, based on specific built-in parameters (or equivalent report properties). This query executer is registered via JsonQueryExecuterFactory factory class.
In order to prepare the data source, the JSON query executer looks for the JSON_INPUT_STREAM parameter that contains the JSON source objects in the form of an java.io.InputStream. If no JSON_INPUT_STREAM parameter is provided, then the query executer looks for the alternate net.sf.jasperreports.json.source String parameter or report property that stores the path to the location of the JSON source file.
JsonQueryExecuter runs the query over the input source and stores the result in an in-memory JsonDataSource object.
So if you do not want to use:
<property name="net.sf.jasperreports.json.source" value="emp.json"/>
You need to pass the file as java.io.InputStream in the parameter JSON_INPUT_STREAM
Hence you are currently passing it as datasource you should try something like this
params.put(JsonQueryExecuterFactory.JSON_INPUT_STREAM, new FileInputStream(file));
JasperFillManager.fillReportToFile(jasperReport, params);
If you instead like to use the new JsonQLQueryExecuterFactory JSONQL Data Source
params.put(JsonQLQueryExecuterFactory.JSON_INPUT_STREAM, new FileInputStream(file));
JasperFillManager.fillReportToFile(jasperReport, params);
If you pass your json string as InputStream then it will works.
String reportContents = "{}" //your json
InputStream is = new ByteArrayInputStream(reportContent.getBytes());
Map params = new HashMap();
params.put(JsonQueryExecuterFactory.JSON_INPUT_STREAM, is);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params);
Take a look here for data source implementation that wraps a collection of JavaBean objects.
List<YourClass> yourBeanCollection = queryDataFromJSON();
JRDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(yourBeanCollection);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,
reportParams, beanCollectionDataSource);
and in the report template import java.util and declare the collection which you "injected" in the report
<import value="java.util.*"/>
<field name="yourBeanCollection" class="java.util.List"/>
also take a look here for an example
Related
I have a pretty weird issue regarding JasperReports.
I made a test PDF file, since we have to swap our reporting tools to JasperReports, and I tried to just play around with a static text and another dynamic text field, which contains one single java.Math.BigDecimal (tried it with another Integer variable, though).
Here's the issue:
Both the static text field (which should contain "troll", yeah...creative) and the dynamic text field are printed in the final exported PDF....although, both the first character of this text field and the length are quite fine, but everything after the first character is just filled up with the same character...means: instead of "troll" it will print "ttttt" and instead of any number (even decimals) between 30000.00-39999.99 will be printed as "33333333" (yep, even the dot will be subbed with a "3").
Here's the source code of the test-PDF-jrxml:
<!-- Created with Jaspersoft Studio version 6.17.0.final using JasperReports Library version 6.17.0-6d93193241dd8cc42629e188b94f9e0bc5722efd -->
<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="Blank_A4" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="7d73e29c-3d01-4b41-9f1e-a969f0f9e3fc">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
<queryString>
<![CDATA[]]>
</queryString>
<field name="cases" class="java.lang.Integer"/>
<field name="sum" class="java.math.BigDecimal"/>
<background>
<band splitType="Stretch"/>
</background>
<pageHeader>
<band height="66">
<staticText>
<reportElement x="206" y="36" width="100" height="30" uuid="0855f093-7bf7-44d3-986b-2cffbca10f96"/>
<text><![CDATA[troll]]></text>
</staticText>
</band>
</pageHeader>
<detail>
<band height="139" splitType="Stretch"/>
</detail>
<summary>
<band height="42" splitType="Stretch">
<textField>
<reportElement isPrintRepeatedValues="false" x="100" y="1" width="271" height="30" uuid="778cb21b-f90f-486d-82cc-91fce9edfc3c"/>
<textFieldExpression><![CDATA[$F{sum}.floatValue(); $F{cases}.intValue();]]></textFieldExpression>
</textField>
</band>
</summary>
</jasperReport>
And the method of our Java-Code which should handle creating the PDF-file.
private void jasperWriteList(final Document pDoc) {
PaymentClass payment= pDoc.getGrpHdr().getPayment();
String path = randomPathDummyHere;
BigDecimal sum = BigDecimal.ZERO;
int cases= 0;
try {
//Compiles jrxml-draft for sum list
JasperReport jasperReport = JasperCompileManager.compileReport("Blank_A4.jrxml");
//Parsing from original
for (PaymentCase pCase : pDoc.getCases().getCase()){
cases++;
sum = sum.add(pCase.getSum());
}
//DataSource and stuff
SumListJRData slData = new SumListJRData(sum, cases);
JRDataSource dataSource = new JRBeanCollectionDataSource(Collections.singletonList(slData));
Map<String, Object> params = new HashMap<>();
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, (JRDataSource)dataSource);
//WE SUSPECT THE ERROR IN THIS VERY STEP, SINCE DEBUG HAS SHOWN PERFECTLY FINE VARIABLES TILL HERE
JasperExportManager.exportReportToPdfFile(jasperPrint, path);
} catch (JRException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
We tried to debug this one, and you can see in the comment of the code, where we suspect the error to be. But we had to dig deeper into the source code than in Minecrafts Nether and still weren't able to find the error. Maybe it's a bug inside of the Jasper package itself? Or did we do something wrong somewhere?
Our tech stack is:
Jaspersoft Studio 6.17.0
Java JDK 1.8.0_292
Eclipse Spring Tool Suite 4 (4.5.0.RELEASE)
Thanks in advance :)
I am trying a simple example to generate a PDF from a .jasper report created in JasperSoft Studio.
I created an empty report, with absolutely nothing (to test - teste_vazio.jasper/ teste_vazio.jrxml).
I generated the .jasper file through Jasper Studio itself.
I created a Java project. I added the following libraries:
com.lowagie.text-2.1.7.jar
commons-beanutils-1.9.4.jar
commons-collections4-4.4.jar
commons-digester-2.1.jar
commons-logging-1.2.jar
itext-2.1.7.jar
jasperreports-6.12.1.jar
jasperreports-annotation-processors-6.16.0.jar
jasperreports-custom-visualization-6.16.0.jar
jasperreports-fonts-6.12.1.jar
jasperreports-functions-6.16.0.jar
jasperreports-javaflow-6.16.0.jar
jasperreports-metadata-6.16.0.jar
joda-time-2.10.10-no-tzdb.jar
joda-time-2.10.10.jar
And I developed the following code:
public static void main(String[] args) {
System.out.println("Teste");
generateReport();
}
static void generateReport() {
try(Connection conn = DriverManager.getConnection(URL,USER,PASS) ) {
JasperPrint jasperPrint = JasperFillManager.fillReport(Main.class.getResourceAsStream("teste_vazio.jasper"), new HashMap<String,Object>(),conn);
File file = new File("/Users/julio/Desktop/JasperLibs/relatorio.jrprint");
if (!file.exists()) {
file.createNewFile();
JRSaver.saveObject(jasperPrint, file);
} else {
JRPdfExporter exporterPdf = new JRPdfExporter();
ExporterInput input = new SimpleExporterInput(jasperPrint);
exporterPdf.setExporterInput(input);
exporterPdf.setExporterOutput(new SimpleOutputStreamExporterOutput(new File("/Users/julio/Desktop/JasperLibs/relatorio.pdf")));
exporterPdf.exportReport();
}
} catch (SQLException | JRException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The code of .jrxml is:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.15.0.final using JasperReports Library version 6.15.0-dd49bfb94918336b8321d5507193f0169ead4e95 -->
<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="teste_vazio" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="6cad13ce-e8d7-4cd7-a095-3a1ab64cfe80">
<queryString>
<![CDATA[]]>
</queryString>
<background>
<band splitType="Stretch"/>
</background>
<pageHeader>
<band height="35" splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="61" splitType="Stretch"/>
</columnHeader>
<detail>
<band height="125" splitType="Stretch"/>
</detail>
<columnFooter>
<band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
</jasperReport>
When I run the project I get the following error:
Exception in thread "main" java.lang.ClassCastException: net.sf.jasperreports.compilers.ReportExpressionEvaluationData cannot be cast to [B
at net.sf.jasperreports.engine.design.JRAbstractJavaCompiler.loadEvaluator(JRAbstractJavaCompiler.java:109)
at net.sf.jasperreports.engine.design.JRAbstractCompiler.loadEvaluator(JRAbstractCompiler.java:351)
at net.sf.jasperreports.engine.JasperCompileManager.getEvaluator(JasperCompileManager.java:382)
at net.sf.jasperreports.engine.fill.JRFillDataset.createCalculator(JRFillDataset.java:487)
at net.sf.jasperreports.engine.fill.BaseReportFiller.<init>(BaseReportFiller.java:168)
at net.sf.jasperreports.engine.fill.JRBaseFiller.<init>(JRBaseFiller.java:273)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:79)
at net.sf.jasperreports.engine.fill.JRFiller.createBandReportFiller(JRFiller.java:251)
at net.sf.jasperreports.engine.fill.JRFiller.createReportFiller(JRFiller.java:272)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:114)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:103)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:530)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:491)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:929)
at Main.generateReport(Main.java:46)
at Main.main(Main.java:28)
I think there is some incompatibility in the file generated by Jasper Studio.
Has anyone ever experienced this?
As Alex K suggested, I compiled the report via Java and everything worked perfectly.
Thanks a lot Alex!
Below is the code used to compile, in case anyone needs it!
InputStream jrxmlStream = Main.class.getResourceAsStream("Cherry.jrxml");
JasperReport relatorioCompilado = JasperCompileManager.compileReport(jrxmlStream);
JasperPrint jasperPrint = JasperFillManager.fillReport(relatorioCompilado, new HashMap<String,Object>(),conn);
File file = new File("/Users/julio/Desktop/JasperLibs/relatorio.jrprint");
I'm trying to pass a string parameter "title" and display it in jasper report.
var parameters = mutableMapOf<String, Any>()
parameters["title"] = "My Title"
val jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource)
I have declared parameter in jrxml as this.
<jasperReport name="transactions" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" >
...
<field name="txId" class="java.lang.Long"></field>
...
<parameter name = "title" class = "java.lang.String"></parameter>
...
<textField>
<reportElement x="238" y="0" width="100" height="20"/>
<textElement textAlignment = "Center">
<font size = "22"/>
</textElement>
<textFieldExpression class="java.lang.String">
<![CDATA[$P{title}]]>
</textFieldExpression>
</textField>
...
</jasperReport>
But when I run the report generation it does not recognize parameter tag and gives this error.
net.sf.jasperreports.engine.JRException: org.xml.sax.SAXParseException; lineNumber: 9; columnNumber: 58; cvc-complex-type.2.4.a: Invalid content was found starting with element 'parameter'. One of '{field, sortField, variable, filterExpression, group, background, title, pageHeader, columnHeader, detail, columnFooter, pageFooter, lastPageFooter, summary, noData}' is expected.
at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:302)
at net.sf.jasperreports.engine.xml.JRXmlLoader.loadXML(JRXmlLoader.java:285)
at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:274)
at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:219)
at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:194)
at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:185)
at net.sf.jasperreports.engine.JasperCompileManager.compile(JasperCompileManager.java:288)
at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:575)
at hms.rincewind.merchantportal.service.ReportService.generateReport(ReportService.kt:26)
at hms.rincewind.merchantportal.service.TransactionService.getTransactions(TransactionService.kt:32)
at hms.rincewind.merchantportal.graphql.api.transaction.TransactionQuery$transactions$1.invokeSuspend(TransactionQuery.kt:23)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:561)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:727)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:667)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:655)
Caused by: org.xml.sax.SAXParseException; lineNumber: 9; columnNumber: 58; cvc-complex-type.2.4.a: Invalid content was found starting with element 'parameter'. One of '{field, sortField, variable, filterExpression, group, background, title, pageHeader, columnHeader, detail, columnFooter, pageFooter, lastPageFooter, summary, noData}' is expected.
at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
Can someone help me to fix this issue.
I have to create multiple XY-line charts with different dataset using same chart report template and I also have to use JRBeanCollectionDatasource for it.
Requirements:
1) Should be done using JRBeanCollectionDatasource.
2) Have to use the same chart report template to create multiple charts.
3) Number of charts are not fixed (Here I have problem giving names to Report Parameter in java). Because in ReportParametersMap, they can only have unique key name .
Java:
Coordinates.java
private Number series;
private Number xCoordinate;
private Number yCoordinate;
//Getters & Setters
GenerateReport.java
I am working with Report Book and each report template of the report book is considered as a sub-report. So I am passing XYChartDataSource(java.util.List) to master report book and I would map this parameter with the subreport by using
new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{XYChartDataSource}) as a Datasource Expression.
and in Subreport, I have created a parameter XYChartDataSource(java.util.List) and created fields (series,xCoordinate,yCoordinate) in MainDataset ( used in chart)
List<List<Coordinates>> allchartData = new ArrayList<>();
List<Coordinates> chartData = new ArrayList<>();
chartData.add(new Coordinates(2.08, xCoordinate, yCoordinate));
chartData.add(new Coordinates(2.08, xCoordinate, yCoordinate));
chartData.add(new Coordinates(2.08, xCoordinate, yCoordinate));
allchartData.add(chartData);
.
.
.
chartData.add(new Coordinates(2.12, xCoordinate, yCoordinate));
chartData.add(new Coordinates(2.12, xCoordinate, yCoordinate));
chartData.add(new Coordinates(2.12, xCoordinate, yCoordinate));
allchartData.add(chartData);
.
.
.
for (int i = 0; i < baselineChartData.size(); i++) {
parameters.put("XYChartDataSource", allchartData.get(i));
}
main_report_book.jrxml
<parameter name="XYChartDataSource" class="java.util.List"/>
<part uuid="5e668430-9acd-4835-be21-f4e2902ce33d">
<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">
<subreportParameter name="REPORT_DATA_SOURCE">
<subreportParameterExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{XYChartDataSource})]]></subreportParameterExpression>
</subreportParameter>
<subreportExpression><![CDATA[$P{SUBREPORT_DIR}+"/sub_chart.jasper"]]></subreportExpression>
</p:subreportPart>
</part>
sub_chart.jrxml
<parameter name="XYChartDataSource" class="java.util.List"/>
<field name="xCoordinate" class="java.lang.Double"/>
<field name="yCoordinate" class="java.lang.Double"/>
<field name="series" class="java.lang.Double"/>
<summary>
<band height="405">
<xyLineChart>
<chart evaluationTime="Report" bookmarkLevel="1">
<reportElement x="30" y="98" width="525" height="230" uuid="627d87d6-b675-409c-accb-b2bb3ffb9c80">
<property name="net.sf.jasperreports.chart.domain.axis.tick.interval" value="1"/>
</reportElement>
<chartTitle/>
<chartSubtitle/>
<chartLegend position="Right"/>
</chart>
<xyDataset>
<xySeries autoSort="true">
<seriesExpression><![CDATA[$F{series}]]></seriesExpression>
<xValueExpression><![CDATA[$F{xCoordinate}]]></xValueExpression>
<yValueExpression><![CDATA[$F{yCoordinate}]]></yValueExpression>
</xySeries>
</xyDataset>
<linePlot isShowShapes="false">
<plot/>
<categoryAxisFormat>
<axisFormat/>
</categoryAxisFormat>
<valueAxisFormat>
<axisFormat/>
</valueAxisFormat>
</linePlot>
</xyLineChart>
</textField>
</band>
</summary>
Current Output:
only one chart is being printed, using the regular method.
Expected Output:
Here I am showing two charts(could be more in actual output) , which needs to be generated from same report template in the SAME PDF REPORT:
chart1
chart2
You problem is here:
for (int i = 0; i < baselineChartData.size(); i++) {
parameters.put("XYChartDataSource", allchartData.get(i));
}
Your parameter "XYChartDataSource" will contain last entry in your List, you replace each time in loop see Map.put(K key,V value))
What we need instead is the whole list
parameters.put("XYChartDataSource", allchartData);
However now we can't access directly the List<Coordinates>
On solution to not change your current subreport is to insert another subreport in the middle which will iterate your List<List<Coordinates>> in detail band.
The structure will be
Pass List<List<Coordinates>> allchartData as datasource to this new subreport (sub_charts.jrxml)
Define the field _THIS which is List<Coordinates> in subreport (hence it's iterating your List<List<Coordinates>>)
In detail band include current sub_chart.jrxml and pass $F{_THIS} as datasource
sub_charts.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="sub_charts" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="bc8c76ba-0b85-4522-bf67-4c62ae87202b">
<field name="_THIS" class="java.util.List">
<fieldDescription>_THIS</fieldDescription>
</field>
<detail>
<band height="63" splitType="Stretch">
<subreport>
<reportElement x="0" y="0" width="550" height="60" uuid="b0e761bf-fe02-4a0a-bafb-32d6831b7a13"/>
<dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{_THIS})]]></dataSourceExpression>
<subreportExpression><![CDATA[$P{SUBREPORT_DIR}+"/sub_chart.jasper"]]></subreportExpression>
</subreport>
</band>
</detail>
</jasperReport>
Remember to call this new subreport in your main_report_book.jrxml.
<subreportExpression><![CDATA[$P{SUBREPORT_DIR}+"/sub_charts.jasper"]]></subreportExpression>
The OP Dhruvil Thaker did this great graphical representation of this answer.
I have a strange problem with Jasper Report and XML data sources. I have two reports that works great inside iReport (a preview shows all correct data), but when I run the report with JasperRunManager.runReportToPdfFile, the values show up as null. Funny thing is that one of the two reports have sub reports, and in the sub reports, everything shows up correctly!
I'm using XPath with a query like this:
<queryString language="xPath">
<![CDATA[/rosterArray/list/studentRoster]]>
</queryString>
and I only have one field:
<field name="studentName" class="java.lang.String">
<fieldDescription><![CDATA[studentName]]></fieldDescription>
</field>
And display it:
<detail>
<band height="30" splitType="Stretch">
<textField>
<reportElement x="10" y="6" width="188" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{studentName}]]></textFieldExpression>
</textField>
</band>
</detail>
XML looks like this:
<rosterArray>
<list>
<studentRoster>
<studentName>Robert, Pascal</studentName>
</studentRoster>
</list>
</rosterArray>
And the code to create the generated report:
File xmlFileName = new File(xmlDSFileName());
JRXmlDataSource xmlDS = new JRXmlDataSource(xmlFileName);
xmlDS.setDatePattern("yyyy-mm-dd HH:mm:ss.S z");
File destFile = File.createTempFile(compiledReportName, ".pdf");
String inputFileName = PathUtilities.pathToReport(compiledReportName);
JasperRunManager.runReportToPdfFile(inputFileName, destFile.getPath(), parameters, dataSource);
When you create JRXmlDataSource object, you have to add the xpath select expression defined in querystring tag. In your case, it should be:
JRXmlDataSource xmlDS = new JRXmlDataSource(xmlFileName, "/rosterArray/list/studentRoster");
Regards.