Run Jasper report and export as pdf from Java Swing application

I have made a Java Swing application which produces an xml file with data from a mysql database.

Using that I have successfully made a Jasper (jrxml) report using the Jasper 5.5.0 plugin for NetBeans separately from my Swing application.

To do this I use the prepared xml file as datasource. So I have Jasper report with an xml datasource and one subreport. How can I run that .jasper report from my Swing application and export as a pdf file? As a final message box from my Swing app I get:

<em>"XML file is successfully generated"</em>

I want to make one button on that message box with option:

<em>"Print xml to pdf file"</em> 

Where can I run my Jasper report and export as a pdf?

I have searched for examples using Google, but I can’t find anything useful.

Answer

I found the solution:

import net.sf.jasperreports.engine.JRException;

import net.sf.jasperreports.engine.JasperCompileManager;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperReportsContext;
import net.sf.jasperreports.engine.data.JRXmlDataSource;
public static void main(String[] args) {
 try {
     HashMap hm = new HashMap < > ();
      String filePath = System.getProperty("user.dir") + "\somexmldatasource.xml";
      InputStream inputStream = new FileInputStream(new File(filePath));
      JRXmlDataSource ds = new JRXmlDataSource(inputStream, "/some/xpath/query");
      JasperReport jasperReport;
      JasperPrint jasperPrint;
      jasperReport = JasperCompileManager.compileReport(System.getProperty("user.dir") + "\yourreport.jrxml");
      jasperPrint = JasperFillManager.fillReport(jasperReport, hm, ds);
      JasperExportManager.exportReportToPdfFile(jasperPrint, "someoutputpath\simple_report.pdf");
 } catch (Exception e) {
      e.printStackTrace();
 }

}

for using Jasper in java you must include several JARs from:

c:Program Files (x86)JaspersoftiReport-5.5.0ireportmodulesext

(or some other path of iReport app)

The JARs to include are:

  • commons-collections-3.2.1.jar
  • commons-digester-2.1.jar
  • commons-logging-1.1.jar
  • jasperreports-5.5.0.jar
  • xml-apis.jar
  • commons-beanutils-1.8.2.jar
  • servlet-api-2.4.jar
  • iText-2.1.7.js2.jar

Leave a Reply

Your email address will not be published. Required fields are marked *