Monday, March 3, 2008

Getting serious (Exporting PDF from Jasper)

Ok, ok... Blogging is good for your health :) 
My boss asked me today did I use JFlex and can I provide quick tutorial.
I used JFLex, JCUp... made some compiling efforts back then. But I can't remember a thing.
So, my first effort in getting serious :) will be my work in progress, using JasperReports and IReport.


IReport crash course
Ok, what is important.
Go to View->Fields. Field names are in my example "myObjectAttribute1" and "myObjectAttribute2". I'll use them later in Java for my data source method "getFieldValue(JRField jrField)". And thats all for simple report! :)
Put some static text, some pictures... and your text fields for "myObjectAttributes". Something like this:

Now save as "MyTemplateName.jrxml".
Compile.
Put it where your Java code can find it.
That's all.
What you need in your Java code
First you need a DataSource for your report. I needed swing table in my report so I'm getting my table model  ArrayList and making MyDataSource:

  1.    
  2. public class CustomJasperDataSource implements JRDataSource {  
  3.   
  4. MyObjectInMyTableClass chartEntry;  
  5.   
  6. Iterator iterator;  
  7.   
  8. ArrayList chartEntries;  
  9.   
  10. public CustomJasperDataSource(ArrayList chartEntries) {  
  11. this.chartEntries = chartEntries;  
  12. iterator = chartEntries.iterator();  
  13. }  
  14.   
  15. public Object getFieldValue(JRField jrField) throws JRException {  
  16. if (jrField.getName().equalsIgnoreCase("myObjectAttribute1")) {  
  17.  return chartEntry.getMyObjectAttribute1();  
  18. }  
  19. if (jrField.getName().equalsIgnoreCase("myObjectAttribute2")){  
  20.  return chartEntry.getMyObjectAttribute2();  
  21. }  
  22. ...  
  23. return null;  
  24. }  
  25.   
  26. public boolean next() throws JRException {  
  27. boolean hasNext = iterator.hasNext();  
  28. if (hasNext) {  
  29.  chartEntry = (MyObjectInMyTableClass) iterator.next();  
  30. }  
  31. return hasNext;  
  32. }  
  33.   
  34. }  

Invoking Jasper
This is called when you press some swing button:
  1.    
  2. protected void jButtonCreatePdfActionPerformed(ActionEvent e) {  
  3.   
  4.  JasperPrint jp = generateReport(myArrayListOfData);  
  5.  JasperViewer jasperViewer = new JasperViewer(jp, false);  
  6.  jasperViewer.setVisible(true);  
  7.   
  8. }  

And this is how generateReport method looks like:
  1.    
  2. private JasperPrint generateReport(ArrayList data) {  
  3.     JasperPrint jasperPrint = null;  
  4.     String templateName = "MyTemplateName.jasper";  
  5.     try {  
  6.         jasperPrint = JasperFillManager.fillReport(templateName,  
  7.                 new HashMap(), new CustomJasperDataSource(data));  
  8.     } catch (JRException e) {  
  9.                   doSOmeExcCatching();  
  10.     }  
  11.     return jasperPrint;  
  12. }  

No comments: