How to generate a PDF in Java with a .jasper file?

2

I am using JasperSoft to create my reports, I use a table to show the data I need, which is fed directly from the database through a query. By looking at the preview inside Jaspersoft it shows the data correctly, I compile the report and I create a .jasper file. What I need to know is how to show this report in my Java application in PDF format.

* Note: I do not want to feed the report from the application, because as I mentioned the table is filled by a query.

    
asked by Troika 12.02.2016 в 18:38
source

5 answers

3

To answer your question well we need to clarify what product you are using, Jaspersoft is a company, not a product. For example, when you say "the preview inside Jaspersoft", we do not know if you mean the Jaspersoft® Studio designer or the JasperReports® Server report server.

Reports are usually designed in Jaspersoft® Studio or IReport®, and are saved in a file .jrxml , that file is compiled .jasper and the latter can be converted to a multitude of formats, including PDF. The conversion of .jrxml to .jasper to PDF can be done from the same Studio, in the JasperReports® Server or from your own application using JasperReports® Library, this last scenario is the one that we have been trying to solve.

In any case I include my code, (by the way, you have not told us if it is a web or desktop application, this example is from a web application)

//Prefiero usar el .jrxml a la aplicacion que el .jasper por que es mas facil de versionar
String sourceFileName = rutaFisica + "MiReporte.jrxml";            
File theFile = new File(sourceFileName);
JasperDesign jasperDesign = JRXmlLoader.load(theFile);//Se carga el archivo

//Si el reporte va a tener un query fijo, puedes omitir este paso
JRDesignQuery newQuery = new JRDesignQuery();
newQuery.setText("SELECT * FROM miTabla WHERE X = Y");
jasperDesign.setQuery(newQuery);

Map parameters = new HashMap();//Parametros que usa el jasperreports
//Este parametro sirve para meter una funcion que el reporte va a ejecutar para encontrar la ruta fisica de sus imagenes
parameters.put("REPORT_FILE_RESOLVER", new FileResolver() {
                public File resolveFile(String fileName) {
                    return new File(getServletContext().getRealPath("") + "\mis_imagenes\"+fileName); 
                }
            });
//Se compila el archivo a .jasper
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

//Aqui se llena el reporte (se ejecuta la consulta)
JasperPrint print = new JasperPrint();
print = JasperFillManager.fillReport(jasperReport, parameters, getConnection());
byte[] pdfBytes = JasperExportManager.exportReportToPdf(print);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline;filename=" + nombreArchivo + ".pdf");
response.getOutputStream().write(pdfBytes);
response.flushBuffer();

Finally, seeing your final grade:

  

* Note: I do not want to feed the report from the application, because as I mentioned the table is filled by a query.

And looking at the editions of your question

  

I have not found a way to generate the report within JAVA; the codes that I found on the internet are from people who fill their reports from the application, but I'm already filling it directly from Jaspersoft

makes me believe (and correct me if I'm wrong) that you think that the .jasper file already includes the data with which the report is fed, and that it is not "feed" by the application, the .jasper file is so only the compiled version of the .jrxml file, if you open the latter with a text editor, you will see that the definition of your query is found ( SELECT * FROM ... ) but no your data, the report should be connected to the database every time the PDF is generated, that's why the getConnection() in my example.

Or maybe none of us understood you, and the only thing you want is to link your JasperReports® Server to your web application.

Please answer, even if you already solved the problem. To get rid of the doubt.

Greetings.

    
answered by 04.06.2016 в 05:39
2

Original answer in SO English: link

  

Let's see, here's how it works: JasperFillManager returns a JasperPrint object, then:

// obtenemos la plantilla JRXML como un stream
InputStream template = JasperReportsApplication.class
    .getResourceAsStream("/sampleReport.xml");
// compilamos el reporte desde el stream
JasperReport report = JasperCompileManager.compileReport(template);
// llenamos el reporte en un print object, listo para exportar
JasperPrint print = JasperFillManager.fillReport(report, new HashMap<String, String>());
// Lo exportamos!
File pdf = File.createTempFile("output.", ".pdf");
JasperExportManager.exportReportToPdfStream(print, new FileOutputStream(pdf));
     

Enjoy!

    
answered by 12.02.2016 в 19:02
0

Instead of passing the data from Java, you need to pass the connection string so that it executes the query that it has inside, that you mention that already generate your report correctly

jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conexion);

More or less complete would be

Map<String, Object> parameters = new HashMap<String, Object>();// Creamos mapa de parametros de ayuda
parameters.put("algunParametro", x);
parameters.put("tipo", y);
Connection conexion = crearConexion(); // creamos la conexion a la base de datos
jasperReport = (JasperReport) JRLoader.loadObjectFromFile(rutaArchivo);//Cargamos al jasper    

jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conexion);// llenamos el reporte, indicando la conexion a base de datos

JRPdfExporter pdfExporter = new JRPdfExporter(); //Creamos el exporter a PDF
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);//EDIT 
exporter.exportReport();
return baos.toByteArray(); //y obtenemos los valiosos bytes generados ;)

In my case, I always like to return the report's byte array, but using other methods you can handle it in a different way.

    
answered by 12.02.2016 в 19:11
0

What I use is in a class (AbstractaJasperReports):

/**
* reporte como tal del sistema de archivos
*/
private static JasperReport report;

/**
* reporte, pero ya lleno con la información que trae el query interno
*/
private static JasperPrint reportFilled;

/**
* visor donde se va a mostrar el reporte
*/
private static JasperViewer viewer;    

public static void crearInforme(Connection conexion, String ruta, Map parametros)
{
  try
  {
    report = (JasperReport) JRLoader.loadObjectFromFile(ruta);
    reportFilled = JasperFillManager.fillReport(report, parametros, conexion);
  } catch (JRException e)
  {
    e.printStackTrace();
  }
}

public static void verVisor()
{
  viewer = new JasperViewer(reportFilled, false);
  viewer.setVisible(true);
}

And then to call it I do:

// creo la conexión a la BBDD
ConexionBBDD conn = new ConexionBBDD();

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

parametros.put("clave", valor);

AbstractaJasperReports.crearInforme((Connection) conn.getConexion(), "./src/rutaAlJasper/ficheroJasper.jasper", parametros);

AbstractaJasperReports.verVisor();
    
answered by 15.02.2016 в 10:49
0

It is possible to integrate a java web application with netbeans and the JasperReports Server application, and from the web application obtain the reports that are in JasperReport Server in PDF or another format with a single button or a request from the web application.

Greetings.

    
answered by 01.08.2016 в 22:58