Ok here’s how to do it.
Firstly you’ll need a Jasper Reports Engine Class.
Create a new class in your project.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package PHJ;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.ResultSet;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPdfExporter;
/**
*
* @author paulc
*/
public class PHJJasperReportEngine {
private databasesettings MyDB=new databasesettings();
// private static final String PREFIX = "/WEB-INF/reports/";
private static final String PREFIX = "";///faces/";
/**
* <p>Suffix to the resource name for compiled reports.</p>
*/
private static final String SUFFIX = ".jasper";
/**
* <p>Valid content types for reports that we can produce.</p>
*/
private static final String[] VALID_TYPES = {"text/html", // Standard HTML representation
"application/pdf", // Adobe Portable Document Format
"application/rtf"};
public byte[] iceFacesjasperReport(String sBaseURL,String sSQL,String name, String type, Map params) throws IOException {
URL url=null;
ByteArrayOutputStream returnStream=new ByteArrayOutputStream();
System.out.println(sBaseURL);
try {
url = new URI(sBaseURL+"/"+name+SUFFIX).toURL();
} catch (URISyntaxException ex) {
Logger.getLogger(PHJJasperReportEngine.class.getName()).log(Level.SEVERE, null, ex);
}
ResultSet data=null;
try {
data = MyDB.getDataFromMYSQL(sSQL);
} catch (ClassNotFoundException ex) {
System.out.println("Class not found "+ex);
}
if (data==null) {
System.out.println("Error in SQL "+sSQL);
return null;
}
// Validate that we recognize the report type
// before potentially wasting time filling the
// report with data
boolean found = false;
for (int i = 0; i < VALID_TYPES.length; i++) {
if (VALID_TYPES[i].equals(type)) {
found = true;
break;
}
}
if (!found) {
throw new IllegalArgumentException("Invalid report type '" + type + "' requested");
}
// Look up the compiled report design resource
InputStream stream = url.openStream();
if (stream == null) {
throw new IllegalArgumentException("Unknown report name '" + name + "' requested");
}
try {
data.beforeFirst();
} catch (Exception e) {
throw new FacesException(e);
}
// Fill the requested report with the specified data
JRResultSetDataSource ds = new JRResultSetDataSource(data);
JasperPrint jasperPrint = null;
try {
jasperPrint = JasperFillManager.fillReport(
stream, params, ds);
} catch (RuntimeException e) {
System.out.println(e);
throw e;
} catch (Exception e) {
System.out.println(e);
throw new FacesException(e);
} finally {
try {
stream.close();
} catch (IOException e) {
}
}
// Configure the exporter to be used, along with the custom
// parameters specific to the exporter type
JRExporter exporter = null;
// PersistentFacesState response=(PersistentFacesState)econtext.getResponse();
//FacesContext fcontext = FacesContext.getCurrentInstance();
try {
// response.setContentType(type);
if ("application/pdf".equals(type)) {
exporter = new JRPdfExporter();
// response.setHeader("Content-Type", "application/download");
// response.setHeader("Content-Disposition", "attachment; filename=" + name + ".pdf");
exporter.setParameter(JRExporterParameter.JASPER_PRINT,
jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
returnStream);
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
// Enough with the preliminaries ...
// export the report already
try {
exporter.exportReport();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
// Tell JavaServer Faces that no output is required
return returnStream.toByteArray();
}
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
int len = 0;
while ((len = input.read(buf)) > -1) output.write(buf, 0, len);
return output.toByteArray();
}
}
Then create a new page. You then need to add an OUTPUT RESOURCE component. I do this in the JSP tab because it doesn’t have any properties.
<ice:outputResource attachment="true" fileName="subcontractorsummary.pdf" id="pdf-button" label="Output to PDF" mimeType="application/pdf"
resource="#{FRIMICESUBCONTRACTORSUMMARY.pdfResource}"
style="height: 24px; left: 24px; top: 168px; position: absolute; width: 119px" type="button"/>
In this case the page is called FRIMICESUBCONTRACTORSUMMARY so you’ll need to change that to match.
Now in the Java backing bean.
private Resource pdfResource;
public Resource getPdfResource() {
return pdfResource;
}
public void setPdfResource(Resource pdfResource) {
this.pdfResource = pdfResource;
}
class MyResource implements Resource, Serializable {
public String sURL;
private String resourceName;
private final Date lastModified;
private ExternalContext extContext;
private PHJJasperReportEngine thisEngine = new PHJJasperReportEngine();
public MyResource(ExternalContext ec, String resourceName) {
this.extContext = ec;
this.resourceName = resourceName;
this.lastModified = new Date();
}
/**
* This intermediate step of reading in the files from the JAR, into a
* byte array, and then serving the Resource from the ByteArrayInputStream,
* is not strictly necessary, but serves to illustrate that the Resource
* content need not come from an actual file, but can come from any source,
* and also be dynamically generated. In most cases, applications need not
* provide their own concrete implementations of Resource, but can instead
* simply make use of com.icesoft.faces.context.ByteArrayResource,
* com.icesoft.faces.context.FileResource, com.icesoft.faces.context.JarResource.
*/
public InputStream open() throws IOException {
try {
// getrequestservletpath retruns the page url
// getRequestContextPath=/CourierSystem
HttpServletRequest thisRequest=(HttpServletRequest) extContext.getRequest();
sURL="http://"+thisRequest.getServerName()+":"+thisRequest.getServerPort()+extContext.getRequestContextPath();
Map param = new HashMap();
/***********************************************/
/* THIS IS THE BIT YOU NEED TO CHANGE FOR YOUR */
/* REPORT - Make sure the filename.jasper is in*/
/* the same place as your icefaces pages */
/* lastly, make sure the SQL matches */
/***********************************************/
String sReportFileName="RPTCUSTOMERJOBSUMMARY";
String sSQL = "SELECT * FROM TBLCUSTOMERS";
/************************************************/
return new ByteArrayInputStream(thisEngine.iceFacesjasperReport(sURL, sSQL, sReportFileName, "application/pdf", param));
} catch (Exception e) {
System.out.println("Error " + e);
}
return null;
}
public String calculateDigest() {
return resourceName;
}
public Date lastModified() {
return lastModified;
}
public void withOptions(Options arg0) throws IOException {
}
}
And then add to the init() phase of the page.
try {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
pdfResource = new MyResource(ec, "report.pdf");
} catch (Exception e) {
e.printStackTrace();
}
Bingo!
Posted by pncblessed
Posted by pncblessed
Posted by pncblessed