Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / Swing

Add Save functionality in ReportCat

5.00/5 (1 vote)
12 Sep 2013Public Domain2 min read 10.3K  
Add Save functionality in ReportCat, a Java print library.

Introduction  

Once I got a chance to work with the ReportCat (http://www.netcat.li/java-report-printing-library/). ReportCat is a very effective Java report print library. It gives you some cool features to generate report. It gives you a interface to preview/zoom in/out, scale in/out and also print the document. It covers all the features except Save which is a very important feature as I believe.

In ReportCat there is no feature to save the document for feature reference. The purpose of this article is to add the save functionality in the ReportCat API. May be there are other way to save this, but what I have done, I just want to share it.

Background 

If you look in to the source of the API, you can find that ReportCat write(more precisely drawing) everything using the Java graphics. And that is the point where you can hook to save the document. The main concept behind the save is to capture the graphics object, create an image and finally save it as PDF.

Using the code

First of all we need a class which has capable to create the PDF. To create the PDF I choose iTextpdf. It is open source and very easy to use. You can download it from http://itextpdf.com/download.php. CreatePDf is a simple class which will take list of java.awt.Image as input and create a PDF as output. Here is the CreatePdf class:

Java
//CreatePdf.java
//please add the neccessary imports
public class CreatePdf {
    public static void createPdf(int w, int h, String file, 
           List<Image> listImage) throws Exception {
        Rectangle pageSize = new Rectangle(0, 0, w, h);
        Document document = new Document(pageSize, 2, 2, 2, 2);
        try {
            PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            com.itextpdf.text.Image image = null;
            boolean firstFlag = true;
            for (Image img : listImage) {
                try {
                    image = com.itextpdf.text.Image.getInstance(img, null);
                } catch (BadElementException ex) {
                    ex.printStackTrace();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                try {
                    if (document != null && image != null) {
                        if (!firstFlag) {
                            document.newPage();
                        }
                        document.add(image);
                        firstFlag = false;
                    }
                } catch (DocumentException ex) {
                    ex.printStackTrace();
                }
            }
        } finally {
            if (document != null) {
                document.close();
            }

        }
    }
}

Our PDF writer class is ready to use. Now we have to add the save functionality into the ReportCat library. If you look in to the api source you can find a class named as PrintManager.java inside li.netcat.print package. In this class you have to add the following piece of code :

Java
/**
* To save as PDF
*/	
public void save()
        throws PrinterException {

    JFileChooser fileChooser = new JFileChooser("C:/");

    int retrival = fileChooser.showSaveDialog(null);

    if (retrival == JFileChooser.APPROVE_OPTION) {
        System.out.println(fileChooser.getSelectedFile());

        try {
            List<Image> imageList = new ArrayList<Image>();
            BufferedImage bImg = null;
            Graphics2D cg = null;

            for (Object painter : d) {
                bImg = new BufferedImage(getPaperWidth(), 
                              getPaperHeight(), BufferedImage.TYPE_INT_RGB);
                cg = bImg.createGraphics();
                cg.setColor(Color.white);
                cg.fillRect(0, 0, getPaperWidth(), getPaperHeight());

                ((Painter) painter).paint(cg, getImageableX(), getImageableY());
                imageList.add(bImg);
                cg.dispose();
            }
            CreatePdf.createPdf(getPaperWidth(), getPaperHeight(), 
              fileChooser.getSelectedFile() + ".pdf", imageList);
            JOptionPane.showMessageDialog(null, "File saved successfully.");

        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }
}

The final task is to expose this feature in the GUI end . To do this you have ro modify the PrintPreview.java. This class is a example class you can find it inside ReportCat example. This may be different as per your application. So the basic purpose is to call the save button from GUI end. To do that add the following code:

Java
// define a button	
private JButton  _saveButton;
// create the button
buttonPanel.add(_saveButton = createButton(SAVE, "Save as PDF"));

Finally call the save()

public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == _saveButton) {
  try {
    _previewPanel.getPrintManager().save();
  }
  catch (PrinterException x) {
    x.printStackTrace();
  }
}
}

All done. Now your ReportCat has the power to save the document as PDF. 

Environment 

I have tested it in Linux with JDK 1.6 and it is running perfectly.

Keep in Mind

Before modify the ReportCat API source file please make sure that you have the proper license to do that.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication