Skip to main content

How to open a PDF file using ICEpdf Viewer from your Java Application?


Few weeks back I designed an application, where I wanted to display Help content through a PDF file rather than through a textbox in a JPanel, because the help content had complex formula stuffs. So I thought of embedding the PDF file with my swing application itself. But it was too tricky to learn in a short span of time. So I figured out two options to display the help content.
  1. By opening the PDF file using a native PDF Reader in the system, on click of the Help Button in my Java Swing application.
  2. By opening the PDF file using a PDF reader integrated with my application jar package, on click of the Help Button in my Java Swing application.
I dont want to discourage the readers, but to be frank the above two methods didnt work for one bad reason. You need the absolute path of the PDF file to be used in the source code.
One solution would be to load a PDF file from a Web link. Another solution would be to use an installation wizard (See here) for your Java application to place the PDF file in predetermined path, so that you can be sure that you have referred the correct path in your source code.

Method 1 : Using Native PDF Reader

The code for my Help Button looks like this
   1: private void jButton17ActionPerformed(java.awt.event.ActionEvent evt) {

   2:     pdfopener pdfo = new pdfopener();

   3:     pdfo.helpview();

   4:     }

I am calling the helpview() method of pdfopener class to open the pdf file. Lets look in to the pdfopener class.

   1: package metrics.wizard;

   2:  

   3: import java.awt.Desktop;

   4: import java.io.File;

   5: import javax.swing.JOptionPane;

   6:  

   7: public class pdfopener {

   8:  

   9:     public void helpview() {

  10:         File pdffile = new File("C:/", "sample.pdf");

  11:  

  12:         try {

  13:             Desktop.getDesktop().open(pdffile);

  14:  

  15:         } catch (Exception ex) {

  16:             JOptionPane.showMessageDialog(null, "Unable to load the help file", "File Read Error", JOptionPane.ERROR_MESSAGE);

  17:         }

  18:  

  19:  

  20:     }

  21: }

I’m using File object to handle this. Note in Line 10 that the first argument we pass in to the Constructor of File object is the predetermined path of the PDF file, the second argument is the name of the PDF File. So for example if the path of your PDF file is C:\Program Files\My Swing App\help.pdf , the argument should be

File pdffile = new File("C:/Program Files/My Swing App/", "sample.pdf");

Note that forward slash “/” should be used instead of “\” while referring the address.
Referring by the address “/sample.pdf” will direct you to the root folder irrespective of the Operating System. In case of Windows Operating Systems, “/” will refer to C:\ usually.

You can also notice that I have used try catch statement in Line 16 to handle exceptions. It will do nothing but display user with a presentable Error message.

Method 2 : Using Integrated PDF Reader with your Swing Application

Imagine a scenario where your end user doesn’t have a PDF reader installed in their system. In that case you can supply a PDF reader along with your application to open the PDF file. You need not develop your own PDF reader, thanks to third party tools providers like ICESoft. You can use the ICEpdf Viewer to enable PDF reader capabilities for your Java Application.

First you need to download the ICEpdf Viewer tools from here http://www.icesoft.org/downloads/icepdf-downloads.jsf . You could notice that their entire site is made of Java Server Faces, a cool Java technology to build Rich Web pages. Let get back to our topic. Download the binary release of ICEpdf viewer. Unzip the contents. In the unzipped content you can find two jar files icepdf-core.jar and icepdf-viewer.jar in the following path ICEpdf-4.3.3-bin\icepdf\lib\ . These are the files that we need now.

ICEpdf Viewer Extracted  Files

Copy those two files to some location of your preference. I used to copy them in to a folder named Library under My Documents. Now you need to import these files in to your Project.

I’m using Netbeans to develop my application, so I will guide you on how to import the library in to your Netbeans Java Swing project. Right Click on the Project Name in Project Explorer Pane and then Select Properties. Under Categories, select Libraries. Then Click on Add JAR/Folder and select the two jar files that you have extracted. The imported files will look like in below screenshot.


ICEpdf Viewer Imported Library

Now getting back to the Project, the code will vary from Method 1 only for the helpview() method. The helpview() source code is given below

   1: /*

   2:  * To change this template, choose Tools | Templates

   3:  * and open the template in the editor.

   4:  */

   5: package metrics.wizard;

   6:  

   7: import java.net.URISyntaxException;

   8: import javax.swing.JFrame;

   9: import javax.swing.JPanel;

  10: import org.icepdf.ri.common.ComponentKeyBinding;

  11: import org.icepdf.ri.common.SwingController;

  12: import org.icepdf.ri.common.SwingViewBuilder;

  13:  

  14: /**

  15:  *

  16:  * @author greenxgene

  17:  */

  18: public class pdfopener {

  19:  

  20:     public void helpview() throws URISyntaxException {

  21:  

  22:         String filepath = "C:/sample.pdf";

  23:  

  24:  

  25:  

  26: // build a controller

  27:         SwingController controller = new SwingController();

  28: // Build a SwingViewFactory configured with the controller

  29:         SwingViewBuilder factory = new SwingViewBuilder(controller);

  30:         JPanel viewerComponentPanel = factory.buildViewerPanel();

  31: // add copy keyboard command

  32:         ComponentKeyBinding.install(controller, viewerComponentPanel);

  33:  

  34: // add interactive mouse link annotation support via callback

  35:         controller.getDocumentViewController().setAnnotationCallback(

  36:                 new org.icepdf.ri.common.MyAnnotationCallback(

  37:                 controller.getDocumentViewController()));

  38:  

  39: // Use the factory to build a JPanel that is pre-configured

  40: //with a complete, active Viewer UI.

  41:  

  42: // Create a JFrame to display the panel in

  43:         JFrame window = new JFrame("Metrics Wizard Help");

  44:  

  45:         window.getContentPane().add(viewerComponentPanel);

  46:         window.pack();

  47:  

  48:         window.setVisible(true);

  49:  

  50: // Open a PDF document to view

  51:         controller.openDocument(filepath);

  52:     }

  53: }

You can notice that we are declaring a String variable to hold the file path in Line 22. Unlike in method the the file path and file name can be included in the same variable. the rest of the codes are for building the pdf viewer from the library. The variable with the file name and path is passed on to the viewer at Line 51.

Also note that the declaration at Line 43 provides the title for the PDF File.

The code for Help button that launches the PDF file will be same as in Method 1, so once you launch the PDF File through ICEpdf Viewer it will look like in the below screenshot.

PDF File Viewed with ICEpdf Viewer

Hope this will be useful for building your application with PDF capabilities. Please feel free to post your opinions or queries.

Comments

Popular posts from this blog

How to use JCalendar date picker in your Java Swing Applications with NetBeans

If you are one of those JAVA beginners like me who wants to implement a datepicker module in your experimental/business critical application developed with NetBeans IDE , then this for you. Let me share how I figured out to do so in simple steps with a sample code. Assuming that you have your Java Swing application ready, you will need to download the JCalendar package from here http://www.toedter.com/en/jcalendar/index.html . The page lists out various modules available with descriptions like JDateChooser, JCalendar, JYearChooser, JMonthChooser, JDayChooser, JSpinField and JLocaleChooser. The one I chose for my app was JDateChooser. After downloading and opening the ZIP file, you can see a whole set of files in it. The one we need is in the folder ‘lib’ with the name jcalendar-1.4.jar (this is the latest version while I was writing this). extract that file to your folder of comfort. The jar file you just extracted contains everything you need to implement the date picker in y

Configuring Google Cardboard to work with Ant VR Headset for Lenovo Vibe K4 Note

Let me make it short. Open the Google Cardboard app from your Lenovo Vibe K4 Note. Go to Switch Viewer option and scan the following QR code. This makes Google Cardboard app to work perfectly with Ant VR Headset. Thanks to this Quora thread . Note : Dont use the inbuilt VR mode and Google Cardboard together. VR mode tries to make the whole android experience viewable through VR headset whereas Google Cardboard only produces VR experience for selective apps with Cardboard compatibility. So they dont work at the same time. Nothing goes wrong even if you activate them together, you only see VRception. Dont use default Ant VR app As mentioned in the Quora thread, dont use Ant VR app. It looks fishy and amateurish. May be its even a spying venture of PLA. who knows. Difference between 360 and 3D videos? If you open 360 videos from Google Cardboard you can watch selected 360 videos (like this one ), where you can rotate your head and look everywhere within t

Honda CB Twister India : A Quick Review

I came across a dozen reviews of Honda CB Twister on web and finally decided to buy it. I owned it on last March, 2012. It costed around ₹63,000 with disc brakes, alloy wheels, road tax and stuffs. The reason why I have included ‘India’ in title is because Twister is also available as Honda CB110 in other countries. Here is my short account on my experience with Twister. Mileage Mileage is a very essential part of my riding experience. I travel around 200 Kms every week, so fuel expenses shouldn't make me bankrupt. Twister’s 60 – 65 KmpL mileage is one of the factors that influenced my choice while buying. Anyway in advertisements its claimed to be 70KmpL.   Engine Nowadays its a increasing trend to see Indians going for high end bikes, but in my case I am good with medium performance engines. Twister’s 110CC engine makes riding smooth up to 55Kmph speed, beyond that Honda Twister turns in to a Honda Vibrator. Considering the fact that I’m not an adrenalized rider,