1
votes

Does JasperReports provide some functions in Java which I can use and change my jrxml.

Like change the font, add new detail section, add static text, delete something, add charts etc.

I want to do them like

someObject.setFont("Arial");

and this will set the object's font to Arial and I can also see the respective change in jrxml.

I know that iReport does this easily without any function call, but I want this thing with Java functions only as I am building some app.

If yes please provide a simple example or sites, links anthing from which I can learn. JasperReports API doc is not so good.

1
So you essentially want to manipulate the JRXML file programatically? You can do that by parsing the JRXML file (it is XML after all) using your favorite XML DOM-parser, manipulate the DOM object representation, and write the JRXML againmkl
@mkl, yes I can do that surely, but isn't that cumbersome and error-prone. Thats why I need a API so when a client says hey I want to change font color on the webpage I will send request to the server where I will use java functions and just say changeFont(...) and it will take care of the rest. I hope I am clear now. :)CoderBoy

1 Answers

1
votes

Yes, JasperReports has an API that allows you to do this. The cornerstone of this is the JasperDesign class, which represents your report in-memory. You should check out the No XML Design Sample, which uses the API extensively to build a report from scratch only using java. Once I had seen that example, I found that by exploring the javadoc from the JasperDesign class, I could quite easily find any method I needed to change elements on a report.

As an example, a basic approach for changing the font on an element would be to first load your JRXML into a JasperDesign object, find the element by its key, then call setFontName:

JasperDesign design = JRXmlLoader.load("path/to/your/JRXML.file");
JRElement element;
for (JRBand band : design.getDetailSection().getBands()) {
    element band.getElementByKey("elementName");
}
if (element != null) {
    ((JRDesignTextElement) element).setFontName("Arial");
}

See this question for how to add a new band. The method of doing so changed in recent versions, so a lot of the examples and tutorials online are out of date.

When you are done modifying/creating your report, you can save it or compile it like so:

JasperCompileManager.writeReportToXmlFile(design, "path/to/your/output.jrxml");
JasperCompileManager.compileReportToFile(design, "path/to/your/output.jasper");