ZeusNet
ZeusNet

Reputation: 720

JasperReport setting parameters

I have some problems with JasperReport. I've generated a *.jrxml File through iReport. There I've definded some fields. Now i want to set these fields in my Java-Application, but it didn't work.

My Code looks like

JasperReport report;
    JasperPrint print;

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

    parameters.put("logoPath", "\\logo.jpg");
    parameters.put("companyName", "Company Name");

    try {
        report = JasperCompileManager
                .compileReport("JRXML\\Template.jrxml");

        for (JRField field : report.getFields()) {
            System.out.println(field.getName() + "|"
                    + field.getValueClassName());
        }

        print = JasperFillManager.fillReport(report, parameters,
                new JREmptyDataSource());
        JasperExportManager.exportReportToPdfFile(print,
                "\\temp\\Example.pdf");

        JasperViewer.viewReport(print);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        Logger.getLogger(Example1.class.getName()).log(Level.ALL,
                e.getLocalizedMessage());

        e.printStackTrace();
    }

The fields are given in the *.jrxml file.

Thanks for your help

Upvotes: 0

Views: 9327

Answers (1)

gresdiplitude
gresdiplitude

Reputation: 1685

You are confusing parameters with fields. A paramater is defined as <parameter name="companyName" class="java.lang.String" isForPrompting="false">, while a field is defined as <field name="companyName" class="java.lang.String"/>. Convert company name to parameter in your jrxml and it should work.

From this tutorial

Parameters

Parameters are object references that are passed-in to the report filling operations. They are very useful for passing to the report engine data that it can not normally find in its data source.

Fields

Report fields represent the only way to map data from the data source into the report generating routines. When the data source of the report is a ResultSet, all fields must map to corresponding columns in the ResultSet object. That is, they must have the same name as the columns they map and a compatible type.

ORIGINAL ANSWER:

Use a FileResolver for logo.jpg, which Jasper will use to resolve files locations.

FileResolver fileResolver = new FileResolver() {
@Override
public File resolveFile(String fileName) {
 URI uri = null;
 try {
uri = new URI(this.getClass().getResource("/" + fileName).getPath());
 } catch (URISyntaxException e) {
 }
return new File(uri.getPath());
}
};

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

parameters.put("logoPath", "\\logo.jpg");
parameters.put("companyName", "Company Name");
parameters.put("REPORT_FILE_RESOLVER", fileResolver);
...
print = JasperFillManager.fillReport(report, parameters,
new JREmptyDataSource());

Upvotes: 3

Related Questions