How do you get a compiled jasper report to load from within the jar file, instead of via a specific path on your hard drive?
My report was working fine on my machine as I had set the path to the reports with:
jasperReport1 = (JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg1.jasper");
jasperReport2 =(JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg2.jasper");
But the reports were not loading when working from the finished jar on a different computer. So I am trying to use Input stream and passing it to JasperFillManager but nothing is working - the InputStream is not finding the files. Have I the path wrong?
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");
My original working code:
private void yTDReportBtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
JasperReport jasperReport1 = null;
JasperReport jasperReport2 = null;
JasperPrint jasperPrint = null;
JasperDesign jasperDesign = null;
Map parameters = new HashMap();
SimpleDateFormat formatter = new SimpleDateFormat("dd-mmm-yyyy");
String today = formatter.format(new java.util.Date());
//load just the compiled jasper files, to save time
//First merge the two jasper reports into one to get page1 and page 2 in same document
jasperReport1 = (JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg1.jasper");
jasperReport2 =(JasperReport) JRLoader.loadObjectFromFile("/Users/admin/Documents/HCCE/Semester 2/OOP/Projects2/TestApp/src/ie/test/OMACYTDReportFinalpg2.jasper");
JasperPrint jp1 = JasperFillManager.fillReport(jasperReport1, parameters,new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
JasperPrint jp2 = JasperFillManager.fillReport(jasperReport2, parameters, new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
List pages = jp2 .getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage)pages.get(j);
jp1.addPage(object);
jp1.setName(unitNameLbl.getText() + " - Financial Year To Date - " + today );
}
JasperViewer.viewReport(jp1, false);
}
catch(Exception ex)
{
System.out.println("EXCEPTION: "+ex.getMessage() + ex);
}
}
And now the changed code that is not working:
private void yTDReportBtnActionPerformed(java.awt.event.ActionEvent evt) {
try
{
JasperReport jasperReport1 = null;
JasperReport jasperReport2 = null;
JasperPrint jasperPrint = null;
JasperDesign jasperDesign = null;
Map parameters = new HashMap();
SimpleDateFormat formatter = new SimpleDateFormat("dd-mmm-yyyy");
String today = formatter.format(new java.util.Date());
//load just the compiled jasper files, to save time
//First merge the two jasper reports into one to get page1 and page 2 in same document
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");
JasperPrint jp1 = JasperFillManager.fillReport(jasper1, parameters,new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
JasperPrint jp2 = JasperFillManager.fillReport(jasper2, parameters, new JRBeanCollectionDataSource(ie.test.BeanFactory.getCalcs()));
List pages = jp2 .getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage)pages.get(j);
jp1.addPage(object);
jp1.setName(unitNameLbl.getText() + " - Financial Year To Date - " + today );
}
JasperViewer.viewReport(jp1, false);
}
catch(Exception ex)
{
System.out.println("EXCEPTION: "+ex.getMessage() + ex);
}
}
Any help greatly appreciated!
Ok update: I got the InputStreams to work by creating a new package called "reports" and using
InputStream jasper1 = getClass().getResourceAsStream("/reports/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("/reports/OMACYTDReportFinalpg2.jasper");
And this works fine in Netbeans BUT it still won't load the files when I compile to jar!!?
Any ideas what I'm doing wrong?
you should put jasper reports in
yourapp/src/main/resources/reports
then you invoke that reports from class java
JasperReport jp = JasperCompileManager.compileReport(getClass().getResourceAsStream("/reports/yourReport.jrxml"));
See you!
Old topic, but could be useful.
I thing where is no src folder inside your jar.
InputStream jasper2 = getClass().getResourceAsStream("/ie/test/OMACYTDReportFinalpg2.jasper");
Where is more advanced way:
Put your jasper reports, images and other resources into jar.
Put YourClass inside jar file and load resources using class.getResourceAsStream() and you need to add loader extention before load resource
(JasperReport) JRLoader.loadObject("stream or path");
// DefaultJasperReportsContext user ExtensionsEnvironment
ExtensionsEnvironment.setThreadExtensionsRegistry(LoaderExtention.INSTANCE);
The following example of loading resources
public class LoaderService
implements RepositoryService
{
public static final RepositoryService INSTANCE = new LoaderService();
#Override
public void setContext(RepositoryContext repositoryContext)
{
}
#Override
public void revertContext()
{
}
#Override
public InputStream getInputStream(String file)
{
LOGGER.fine(String.format("getInputStream('%s')", file));
return <YourClass>.class.getResourceAsStream(file);
}
#Override
public Resource getResource(String file)
{
LOGGER.fine(String.format("getResource('%s') not implemented", file));
return null;
}
#Override
public <K extends Resource> K getResource(String file, Class<K> cls)
{
LOGGER.fine(String.format("getResource('%s', %s)", file, cls != null? cls.getName(): null));
try
{
if (cls == ReportResource.class)
{
InputStream resource = getInputStream(file);
if (resource != null)
{
JasperReport report = (JasperReport) JRLoader.loadObject(resource);
if (report != null)
{
ReportResource res = new ReportResource();
res.setName(file);
res.setReport(report);
return (K) res;
}
}
}
else if (cls == InputStreamResource.class)
{
InputStream resource = getInputStream(file);
if (resource != null)
{
InputStreamResource res = new InputStreamResource();
res.setInputStream(resource);
return (K) res;
}
}
}
catch (JRException e)
{
}
return null;
}
#Override
public void saveResource(String string, Resource resource)
{
// TODO Implement this method
}
}
public class LoaderExtention
implements ExtensionsRegistry
{
public static final LoaderExtention INSTANCE = new LoaderExtention();
#Override
public <T extends Object> List<T> getExtensions(Class<T> cls)
{
ExtensionsRegistry system = ExtensionsEnvironment.getSystemExtensionsRegistry();
List<T> services = null;
if (system != null)
services = system.getExtensions(cls);
if (cls == RepositoryService.class)
{
List<T> servicesAll = new ArrayList<T>();
if (services != null)
servicesAll.addAll(services);
servicesAll.add((T) LoaderService.INSTANCE); // Try to use system resource loaders then my
services = servicesAll;
}
LOGGER.fine(String.format("getExtensions(%s) = %s", cls.getName(), services));
return services;
}
}
I use JasperReport 5.5
Have fun.
InputStream jasper1 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg1.jasper");
InputStream jasper2 = getClass().getResourceAsStream("src/ie/test/OMACYTDReportFinalpg2.jasper");
Related
I used E4XMIResourceFactory to save perspective in my eclipse 4 application. But when I went to load my perspective from xmi file, I could found my data in the part. In other world I'd like to save dirty part inside my xmi file. Somebody can help me I cannot find any resurce online to solve my problem.
public class SaveHandler {
#Execute
public void execute(EModelService modelService, MWindow window, MApplication app, Shell shell) {
MPerspective savePerspective = modelService.getActivePerspective(window);
E4XMIResourceFactory e4xmiResourceFactory = new E4XMIResourceFactory();
Resource resource = e4xmiResourceFactory.createResource(null);
MUIElement clonedPerspective = modelService.cloneElement(savePerspective, window);
resource.getContents().add((EObject) clonedPerspective);
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.xmi"});
//dialog.setFilterPath("c:\\temp");
String result = dialog.open();
FileOutputStream outputStream = null;
try {
// Use a stream to save the model element
outputStream = new FileOutputStream(result);
resource.save(outputStream, null);
if (outputStream != null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And the loader method is
public class OpenHandler {
#Execute
public void execute(EPartService partService,EModelService modelService,MWindow window, MApplication app, Shell shell) {
E4XMIResourceFactory e4xmiResourceFactory = new E4XMIResourceFactory();
Resource resource = e4xmiResourceFactory.createResource(null);
FileInputStream inputStream = null;
try {
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.xmi"});
//dialog.setFilterPath("c:\\temp");
String result = dialog.open();
inputStream = new FileInputStream(result);
resource.load(inputStream, null);
if (!resource.getContents().isEmpty()) {
MPerspective loadedPerspective = (MPerspective) resource.getContents().get(0);
//MPerspective perspective = (MPerspective)modelService.find("ktool_aie.perspective.connectionandmaps",app);
MPerspective perspective = modelService.getActivePerspective(window);
MElementContainer<MUIElement> perspectiveParent = perspective.getParent();
List<MPerspective> alreadyPresentPerspective = modelService.findElements(window,loadedPerspective.getElementId(), MPerspective.class, null);
for (MPerspective i_perspective : alreadyPresentPerspective) {
modelService.removePerspectiveModel(i_perspective, window);
}
// add the loaded perspective and switch to it
perspectiveParent.getChildren().add(loadedPerspective);
partService.switchPerspective(loadedPerspective);
}
if (inputStream != null) inputStream.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
I am able to get image from ms word table but unable to get shapes and clip-arts.
public static void main(String[] args) throws Exception {
// The path to the documents directory.
try {
String dataDir = "E://test//demo.docx";
generatePicturesAsImages(dataDir);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void generatePicturesAsImages(String sourcePath) {
try {
Document doc = new Document(sourcePath);
ImageSaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);
options.setJpegQuality(100);
options.setResolution(100);
// options.setUseHighQualityRendering(true);
List<ShapeRenderer> pictures = getAllPictures(doc);
if (pictures != null) {
for (int i = 0; i < pictures.size(); i++) {
ShapeRenderer picture = pictures.get(i);
String imageFilePath = sourcePath + "_output_" + i + ".jpeg";
picture.save(imageFilePath, options);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static List<ShapeRenderer> getAllPictures(final Document document) throws Exception {
List<ShapeRenderer> images = null;
#SuppressWarnings("unchecked")
NodeCollection<DrawingML> nodeCollection = document.getChildNodes(NodeType.DRAWING_ML, Boolean.TRUE);
if (nodeCollection.getCount() > 0) {
images = new ArrayList<ShapeRenderer>();
for (DrawingML drawingML : nodeCollection) {
images.add(drawingML.getShapeRenderer());
}
}
return images;
}
Above program is getting images from table so what should i add more to get the shapes.. Please suggest me any help will be appreciate !
You are using an older version of Aspose.Words. If you want to use older version of Aspose.Words, please get the collection of Shape and DrawingML nodes using Document.getChildNodes in your getAllPictures method.
NodeCollection<DrawingML> drwingmlnodes = document.getChildNodes(NodeType.DRAWING_ML, Boolean.TRUE);
NodeCollection<Shape> shapenodes = document.getChildNodes(NodeType.SHAPE, Boolean.TRUE);
Note that we removed the DrawingML from our APIs in Aspose.Words 15.2.0. If you want to use latest version of Aspose.Words v16.5.0, please only use NodeType.SHAPE.
I work with Aspose as Developer evangelist.
I'm wondering how I can create a new file with an existing emf resource. At the moment I've the following code in my org.eclipse.ui.menus DefaultHandler, which get me the existing emf resource and create a new (empty) file:
if (element instanceof IResource) {
IResource pldFile = (IResource) element;
String path = pldFile.getLocation().toString();
URI uri = URI.createFileURI(path);
// Obtain a new resource set
ResourceSet resSet = new ResourceSetImpl();
// Get the existing resource
Resource emfResource = resSet.getResource(uri, true);
IProject project = pldFile.getProject();
String fileName = pldFile.getName().replace(pldFile.getFileExtension(), "plc");
IFile plcFile = project.getFile(new Path(fileName));
byte[] bytes = "".getBytes();
try {
InputStream source = new ByteArrayInputStream(bytes);
if (plcFile.exists()) {
int i = 1;
String tmp = "";
do {
tmp = fileName;
int index = tmp.indexOf(".plc");
tmp = tmp.substring(0, index) + i + tmp.substring(index, tmp.length());
plcFile = project.getFile(new Path(tmp));
i++;
} while (plcFile.exists());
plcFile.create(source, IResource.NONE, null);
} else {
plcFile.create(source, IResource.NONE, null);
}
PlcEditorInput input = new PlcEditorInput(emfResource);
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
IDE.openEditor(page, plcFile);
} catch (CoreException e) {
e.printStackTrace();
}
How can I assign now the existing emf resource to my newly created file?
Cheers,
Phil
I'm not sure but try to import the resource as new file. I mean define a new file or project and then import the resource.
To be honestly I try a similary way but it didn't work with my resource(--> it's a 10-years-old-code).
This is my source cord to print my invoice page. My report is in Java package. I kept it inside a folder called "report".
try {
String date1 = new SimpleDateFormat("yyyy-MM-dd").format(isdate.getDate());
String time1 = istime.getValue().toString().split(" ")[3];
date1 = date1 + " " + time1;
String date2 = new SimpleDateFormat("yyyy-MM-dd").format(redate.getDate());
String time2 = retime.getValue().toString().split(" ")[3];
date2 = date2 + " " + time2;
JRTableModelDataSource dataSource = new JRTableModelDataSource(jTable1.getModel());
String reportsource = " D:/Catering/report/report1.jrxml";
Map<String, Object> params = new HashMap<String, Object>();
params.put("inid", txtInvoiceID.getText());
params.put("cuname", txtCuName.getText());
params.put("cuadd", txtCuid.getText());
params.put("cutp", txtTPNo.getText());
params.put("isdate", date1);
params.put("redate", date2);
params.put("advance", txtAdvance.getText());
params.put("due", txtDue.getText());
params.put("total", txtGtotal.getText());
JasperReport jasperReport = JasperCompileManager.compileReport(reportsource);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
JasperViewer.viewReport(jasperPrint, true);
JOptionPane.showMessageDialog(null, "Done");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "jasper error"+e);
}
It would be better make the report an embedded resource, but where possible you should not rely on absolute paths, as these may change between installs...
Try changing
String reportsource = " D:/Catering/report/report1.jrxml";
^---- Did you notice the white space here?
To
String reportsource = "report/report1.jrxml";
It is, also, generally better to pre-compile the report so you don't need to do it at run time...
You could write a simple program that compiled it for you using something like...
String templateFile = "report/report1.jrxml"
String compiledReport = "report/report1.jasper"
JasperCompileManager.compileReportToFile(templateFile, compiledReport);
The method takes two Strings, basically one is the jrxml file and other is the expected jasper file.
You could use JasperReports' Ant task and make apart of your build process.
Or you could use iReports...
Once compiled, you can simply load the jasper file at run time...
String compiledReport = "report/report1.jasper";
JasperReport report = (JasperReport)JRLoader.loadObjectFromFile(compiledReport );
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
Updated with Quick Compile example
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
public class QuickCompile {
public static void main(String[] args) {
try {
String template = "...";
String compiled = "...";
JasperCompileManager.compileReportToFile(template, compiled);
// Just as a test...
JasperReport jr = (JasperReport) JRLoader.loadObjectFromFile(compiled);
} catch (JRException exp) {
exp.printStackTrace();
}
}
}
it works fine in when I run it in Netbeans but it's won't show in executable jar file here's my codes
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
rep.siapkan_report_dengan_parameter("report4.jrxml", "Report", "periode",tCari.getText());
this.setCursor(Cursor.getDefaultCursor());
}
public void siapkan_report_dengan_parameter(
String nama_report,
String direktori,
String namaparameter,
String isiparameter){
konek.openConnection();
Properties systemProp = System.getProperties();
// Ambil current dir
String currentDir = systemProp.getProperty("user.dir");
File dir = new File(currentDir);
String reportName = nama_report;
String reportDirName = direktori;
File fileRpt;
String fullPath = "";
if (dir.isDirectory()) {
String[] isiDir = dir.list();
for (int i = 0; i < isiDir.length; i++) {
fileRpt = new File(currentDir + File.separatorChar + isiDir[i] + File.separatorChar +
reportDirName + File.separatorChar + reportName);
if (fileRpt.isFile()) { // Cek apakah file ada
fullPath = fileRpt.toString();
}
}
}
String[] subRptDir = fullPath.split(reportName);
try {
// Persiapkan parameter untuk Report
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(namaparameter, isiparameter);
try {
JasperReport JRpt = JasperCompileManager.compileReport(fullPath);
JasperPrint JPrint = JasperFillManager.fillReport(JRpt, parameters,konek.conn);
if(JPrint.getPages().isEmpty()){
JOptionPane.showMessageDialog(null,
"Data Untuk Kriteria :\n" + isiparameter +"\nTidak Ada",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}else{
JasperViewer.viewReport(JPrint, false);
}
} catch (Exception rptexcpt) {
JOptionPane.showMessageDialog(null,
"a",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"b",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}
}
thanks in advance!
my libraries are:
common-beanutils-1.7
commons-collections-2.1
commons-digester-1.7
commons-javaflow-20060411
commons-logging-1.1
jasperreports-3.0.1
jdt-compiler-3.1.1
jfreechart-1.0.3
poi-3.0.1-FINAL-20070705
The problem is that you are not loading jasper report as a stream. So, try adding this:
InputStream st = getClass().getResourceAsStream(fullPath);
try {
JasperDesign jd = JRXmlLoader.load(st);
JasperReport JRpt = JasperCompileManager.compileReport(jd);
JasperPrint JPrint = JasperFillManager.fillReport(JRpt, parameters,konek.conn);
if(JPrint.getPages().isEmpty()){
JOptionPane.showMessageDialog(null,
"Data Untuk Kriteria :\n" + isiparameter +"\nTidak Ada",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}else{
JasperViewer.viewReport(JPrint, false);
}
} catch (Exception rptexcpt) {
JOptionPane.showMessageDialog(null,
"a",
"Peringatan",
JOptionPane.ERROR_MESSAGE);
}
Also, add your .jrxml files in some package in your project before you export it to .jar.
Path (fullPath) you will pass will be something like: /com/report/nameofreport.jrxml.
Problem is not with your code... Just add following libraries. Don't use latest jasper libraries. that is the reason to not load your reports through jar executable. (use ireport 5.5.0 libraries). Code i use is below
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
org.apache.log4j.BasicConfigurator.configure(new NullAppender());
//InputStream st = getClass().getResourceAsStream("/Reports/SalesInvoiceCustomerCopy.jrxml");
try
{
Connection connect = conn.open();
String report2 = "H:\\Higher Diploma Project\\FinalHD\\src\\Reports\\SalesInvoiceCustomerCopy.jrxml";
JasperReport rep2 = JasperCompileManager.compileReport(report2);
JasperPrint rep_print2 = JasperFillManager.fillReport(rep2,null,connect);
JasperPrintManager.printReport(rep_print2,false);
String report = "H:\\Higher Diploma Project\\FinalHD\\src\\Reports\\SalesInvoice.jrxml";
JasperReport rep = JasperCompileManager.compileReport(report);
JasperPrint rep_print = JasperFillManager.fillReport(rep,null,connect);
JasperPrintManager.printReport(rep_print,false);
try
{
pst =conn.open().prepareStatement("INSERT INTO invoice_balanace VALUES (?,?,?,?)") ;
pst.setString(1, txtInvoiceNo.getText());
pst.setString(2, txtValue.getText());
pst.setString(3, totDisc.getText());
pst.setString(4, txtNetVal.getText());
pst.executeUpdate();
}catch(Exception e){JOptionPane.showMessageDialog(null, e);}
idUpdater();
}catch(Exception e){JOptionPane.showMessageDialog(null,""+ e);}
}
It is not quite efficient to use a compiled jasper report into your jar file. I'll suggest you reference the report from a location on your pc e.g., C: drive.
It'll also be Best if you have a permanent folder that can be easily accessed. It could be C:/<project name>/report/<your-report>.
This approach enables you to distribute it with ease.