# Lab-6808: Working with PDF and Java

Expected Duration: 120 minutes
Contacts: Duane Nickull

Introduction | Exercise 0 | Exercise 1 | Exercise 2 | Exercise 3 | Exercise 4 | Exercise 5 | Exercise 6 | Exercise 7 | Exercise 8 | Summary
### Exercise 1: Opening and Closing a PDF Document in Java Objective: Learn how to read and serialize a PDF to and from a file system. - Expected duration: 10 minutes - Brief description: Attendees will write a base class and add some code to open a PDF document programmatically in an java environment. Step 1: Start up Eclipse. If this is the first time you have been asked to open up Eclipse, you will be asked to create a new workspace. Recommend that you make the workspace directory with no spaces in it (something like c:\eclipse\workspace (windows) or /Users/YourName/workspace (Unix based systems). When you open up Eclipse for the first time, you may see a welcome screen. Dismiss it by clicking the close icon as shown below. You will next need to create a project. Call your project "JavaOne2009" to be consistent with the instructors screen. This is done in the Eclipse with the following menu choices: File -> New -> Project. If prompted for the type of project, select "java project". (NOTE: If you already have eclipse open in the Java Perspective, you can simply select "New Java Project". This will give you a prompt for the type of project. This Hands on lab uses the defaults shown above. After you have selected this, click "Finish" Step 2: Now that you have a new project, you should see a the Package explorer view as shown below. Step 3: We next need to copy over some files from the Hands on Lab courseware. Browse to the <lab_root> directory. Within your <lab_root>/PutUnderEclipseWorkspace/ folder, there are four main folders as shown below. Copy ONLY these folders: <lab_root>/PutUnderEclipseWorkspace/JavaOne2009_libs goes into your eclipse workspace folder. This contains all the *.jar files you require for this lab. <lab_root>/PutUnderEclipseWorkspace/JavaOne2009/src/org goes into your <eclipse_workspace>/JavaOne2009/src folder. Additionally, copy over the DuanesWorld.pdf file. <lab_root>/PutUnderEclipseWorkspace/JavaOne2009-docs goes into your <eclipse_workspace>/ folder. This folder contains documents of various types we will be working with. OPTIONAL: <lab_root>/PutUnderEclipseWorkspace/JavaOne2009-Completed goes into your eclipse workspace folder. This contains all the solutions for this lab. in Eclipse's Package Explorer, select the "src" directory of your newly created "JavaOne2009" project and right click (control click on Mac) it and select "Refresh" (shortcut F5) from the menu. Next, expand your JavaOne2009/src folder to make sure you have access to all the Hands On Lab files as shown below (don't worry about Red X's at this point). Step 3: The Red X's are there because we have not yet imported the jar files yet. Even after you import the jars files, there are still going to be some red X's. WHen you go to run a class and you get a warning that there are errors in the project, just click "Proceed". 3a– To do this, select the root project folder "JavaOne2009" and right click it (Control click on a Mac). Optionally, on some operating systems, you can select “Project” -> "Build Path" and you will see a window that looks similar to the one below. 3b - Select the “Java Build Path” on the left hand side and click on "Add External Jars" 3c - navigate to the`<lab_root>/PutUnderWorkspace/JavaOne2009_libs` directory, select all the jars and folders and click "Open" as shown below. Now import them into your project by selecting "OK" as shown below: NOTE: XPAAJ.jar is an old and deprecated library. We are only using it to demonstrate some preliminary concepts and will continue most of the lab using the newer LiveCycle ES SDK. The newer SDK is far superior to XPAAJ and it it HIGHLY recommended that developers use the client side java SDK's provided with the developer licensed version of LiveCycle ES for any PDF manipulation. You must get explicit permission if you want to use XPAAJ from Adobe in a commercial environment. It is also no longer supported as the newer SDK's supercede XPAAJ. Step 4: Open up the first project from the Package Explorer entitled "PDFOpen.java" by double clicking on it. It will be under your <eclipse_workspace>/JavaOne2009/src/org/duanesworldtv/livecycle/samples directory. Step 5: The source code will appear as follows. It requires you to add some code to open up the PDF document.

              import java.io.InputStream;

          import java.io.FileInputStream;

          import java.io.FileOutputStream;

          import java.io.BufferedWriter;

          import java.io.FileWriter;

          import java.io.FileNotFoundException;

          import java.io.IOException;

          // this is from xpaaj.jar - check licenses before using.

          // LiveCycle ES has newer JAVA libraries for manipulating PDF

          import com.adobe.pdf.*;
        public class JavaOne2009_1 {

          public static void main(String[] args)

                  throws FileNotFoundException, IOException

            {

                  // get pdf filename

                  String inPdfName;

                  if(args.length != 1 ) {

                    System.out.println("\nCommand line format: java PDFExtractData pdf-file");

                    return;

                  } else {

                        // message

                      System.out.println("\nPDF data extraction using Adobe PDF Libraries.");

                        inPdfName = new String(args[0]);

                        //PDFExtract(inPdfName);

                  }

            }
               /**

             *      TODO: Add Method PDFExtract to open and extract data from PDF file.

             */
        }
        /******* End of file *********************************/
Step 6 – uncomment the line of code that will call the new method we write. This is done by removing the two slashes before it to change it from this:
      //PDFExtract(inPdfName);
to this:
      PDFExtract(inPdfName);
Step 7 - Add the code to build a new method. We are going to use the method “OpenDocument” from the PDFFactory class. The API signature is as follows: Step 8: start your method as follows:

          public static void PDFExtract(String inPdfName)

            throws FileNotFoundException, IOException

            {

            // open PDF

            try {

                  doc = PDFFactory.openDocument(inPdfFile);

            } catch (IOException e) {

                        System.out.println("Error opening PDF file :" + inPdfName);

                        System.out.println(e);

            }
Teachers notes: - explain try..catch and exception handing – make sure attendees understand! Step 9: add the following bold code:

          public static void PDFExtract(String inPdfName)

            throws FileNotFoundException, IOException

            {

            // open PDF

            System.out.println("\nOpen PDF Document ... ");

            PDFDocument doc = null;

            FileInputStream inPdfFile = new FileInputStream(inPdfName);
                try {

                  doc = PDFFactory.openDocument(inPdfFile);

            } catch (IOException e) {

                        System.out.println("Error opening PDF file :" + inPdfName);

                        System.out.println(e);

            }
Teachers notes: - Explain the fileinputstream and the new PDFDocument doc Step 10: append this code to the end of your method:

            if(doc == null)

                  System.out.println("Cannot open PDF file : " + inPdfName);

            else

                  System.out.println( inPdfName + " was successfully opened.");

            }
Step 11: your code should now be ready to run. The completed file should look like this:

        import java.io.InputStream;

          import java.io.FileInputStream;

          import java.io.FileOutputStream;

          import java.io.BufferedWriter;

          import java.io.FileWriter;

          import java.io.FileNotFoundException;

          import java.io.IOException;

          // this is from xpaaj.jar - check licenses before using.

          // LiveCycle ES has newer JAVA libraries for manipulating PDF

      import com.adobe.pdf.*;
        public class JavaOne2009_1 {

          public static void main(String[] args)

                  throws FileNotFoundException, IOException

            {

                  // get pdf filename

                  String inPdfName;

                  if(args.length != 1 ) {

                    System.out.println("\nCommand line format: java PDFExtractData pdf-file");

                    return;

                  } else {

                        // message

                      System.out.println("\nPDF data extraction using Adobe PDF Libraries.");

                        inPdfName = new String(args[0]);

                        PDFExtract(inPdfName);

                  }

            }
               /**

             *      TODO: Add Method PDFExtract to open and extract data from a PDF file

             */

          public static void PDFExtract(String inPdfName)

            throws FileNotFoundException, IOException

            {

            // open PDF

            System.out.println("\nOpen PDF Document ... ");

            PDFDocument doc = null;

            FileInputStream inPdfFile = new FileInputStream(inPdfName);
              try {

                  doc = PDFFactory.openDocument(inPdfFile);

            } catch (IOException e) {

                        System.out.println("Error opening PDF file :" + inPdfName);

                        System.out.println(e);

            }
              if(doc == null)

                  System.out.println("Cannot open PDF file : " + inPdfName);

            else

                  System.out.println( inPdfName + " was successfully opened.");

            }
        }
        /******* End of file *********************************/
Step 12 - Before you run the program, you have to specify arguments so Eclipse knows how to find the args. To do this, select “Run” -> “Run Configuration” from the top menu as shown below. This will open up a dialog window that looks like this. Note: if you do not see this, highlight "java Application" in the left hand pane and click the document icon to add a new configuration. Click on the tab “Arguments” as shown above and you will need to enter the program arguments in the box. The simplest way to do this is to grab a command window (Win) or terminal (*.nix) and first navigate to the absolute Volume root. Be sure to high lite the current project on the left hand side of the dialog box that you want to set the runtime args for. NOTE: This process will be different on Windows and Unix based systems. This can be done by entering “/” as show below: navigate to the directory of`<lab_root>/PutUnderWorkspace/JavaOne2009_docs` then enter “`pwd`” to get the absolute path to that directory as shown below. Copy and paste the result from “pwd” into the arguments and concatenate the name of the *.pdf file you wish to use. In this case you should see one there called DuanesWorld.pdf. The click “Apply”. Eclipse should now know how to get the argument file and pass it to the java class when you run the program. You are now ready to run your program. You should see the following in the eclipse console window: `PDF data extraction using Adobe PDF Libraries.` `Open PDF Document ... /Users/adobe/Desktop/eclipse/workspace/JavaOne2009-1/src/DuanesWorld.pdf was successfully opened.` If you did, congratulations! Proceed to exercise 2 Back to top Next exercise