Generating PDF Documents with Java CAPS Introduction

Generating PDF Documents with Java CAPS Introduction

Generating PDF Documents with Java CAPS Holger Paffrath July 2009 This tutorial will go through how to create a PDF document in Java CAPS. To create the PDF document, we will use an Open Office document as the template and then use Open Office to generate the PDF with calls from Java CAPS. This is handy in generating automated letters or reports and rather than using a flat file allows you to add a little formatting to your report. This example is used to generate a PDF document, but you can use the same call to generate Microsoft Word Documents, HTML pages, RTF pages and other numerous outputs. The differences are only a single parameter value which will be indicated in the tutorial. Introduction Open Office was built using a base technology called UNO (Universal Network Object). This technology allows you to utilize components that interact across different computer languages, platforms and technology. You can access UNO components through the UNO API (Application Programming Interface). This technology thus allows us to interact with OpenOffice which is how we will generate our PDF documents. Therefore for this tutorial, you will need to download and install OpenOffice. The latest version of OpenOffice can be found at http://OpenOffice.org . To give you an overview of what we will be doing in this tutorial, see the diagram below. Java CAPS will be picking up an Open Office Document which will have fields specified. This document will then be streamed to Open Office through the UNO API Calls. Java CAPS will then specify which fields will be populated in the document and their respective values. Java CAPS will request OpenOffice to stream back the populated document to Java CAPS in the specified format. In this case it will be PDF. A Web service will be created to expose the whole process as a service. Open Office Install First off, if you haven't already got open office or StarOffice, install OpenOffice from http://OpenOffice.org. OpenOffice is a free open source alternative to Microsoft Office. It is supported on a number of platforms including Windows, Linux, Mac, Solaris. OpenOffice will quite happily sit on a computer already running Microsoft Office. Alternatively, you do not need to install OpenOffice on the computer that is running Java CAPS. It can be running on a separate system. We just need to have a network connection between the two systems and communication over port 8000 open. Install OpenOffice SDK The OpenOffice SDK (Software Development Kit) gives us the APIs to communicate with UNO. The SDK can be found at http://download.openoffice.org/3.0.0/sdk.html The OpenOffice SDK needs to be installed on the same system that OpenOffice is installed obviously. Running OpenOffice Before we can use anything developed to communicate with OpenOffice, we need to start OpenOffice. Since OpenOffice is to be used as a service, not as an application, we need to start it up in what is known as “Headless” mode. In this mode, OpenOffice runs in the background. Any documents opened by OpenOffice will not be shown on the screen. This gives us a clean runtime environment. The only problem is that if you need to modify the template, you have to kill the headless instance of OpenOffice then you can start OpenOffice normally. To start OpenOffice in Headless mode, enter the following on the command line in the “<OpenOffice>/program” directory. soffice.exe -headless -accept="socket,host=localhost,port=8100;urp;StarOffice.Service" Create Template Before we continue, lets create an OpenOffice document ready for population. If you have started OpenOffice in headless mode as per the above command line, kill the soffice.exe process. You can re-start OpenOffice in headless mode after you have created your template. Create an OpenOffice Document with fields ready for population. Create a new Document in Open Office. For the purposes of this tutorial, I have created a simple form where the Name and address is displayed. In this template, we have areas to put the details, but no place markers, so we'll add them now. Select the “Name” entry box and select “Insert/Fields/Other”. Select the “Variables” tab, then the Type as “Set Variable” and the Format as “Text”. Give the variable a name, in this case “NAME” and a default value. In this case I have given it “%NAME%”. Click “Insert” then “Close”. You will now have a new field in your document with “%NAME% as the value. Repeat this Process for Other Fields giving Street %STREET% City %CITY% PostCode %POSTCODE% State %STATE% Note : There is no relevance to the percentage “%” symbol wrapping the values. I'm just using this as an indicator for the default values. Save your template. OpenOffice Plugin Once we have installed OpenOffice, we now need to install the OpenOffice plugin into Netbeans. Bring up Netbeans and select “Tools” then “Plugins”. You will then see a Dialog box with the installed plugins. Select the “Plugins Settings” tab. Make sure that the “NetBeans Beta” check box is checked. As of writing, the OpenOffice plugin was still in Beta, but works quite well. Once you have checked “NetBeans Beta”, the “Available Plugins” tab will be available if it isn't already and a number of new Plugins will now be available. Click on the “Available Plugins” Tab. Scroll down the list and select the “OpenOffice.org API Plugin” and click the “Install” button on the bottom left of the box. Accept the defaults and license agreement and the plugin should start installing. Once complete, click Finished. The OpenOffice plugin is now installed. To configure the plugin, go to “Tools/Options” Select the “Miscellaneous” Button, then the “OOo API Plugin” tab. Make sure that the “OpenOffice.org Installation” and the “OpenOffice.org SDK Installation” are populated correctly. That's it for the preparation. Now we can start coding. Creating the Wrapper For this implementation, I created a wrapper for the OpenOffice API. This allowed me to hide a lot of the complexity in the Java CAPS implementation. It also allows me to re-use the implementation for future use in JBI projects or basically any other implementation in the future. So lets start by creating a new project. In Netbeans, select “File” then “New Project” Select “OpenOffice.org” then “OpenOffice.org Client Application”. Then click Next. Give the Project a name and Package name, and a location where the project will be saved. Then click “Finish”. You should now have a new project called “OpenOfficeWrapper” or whatever name you gave it previously. As a base for this Wrapper API, I have taken the code written by hol.sten (Great beer!!) which can be found at “http://user.services.openoffice.org/en/forum/viewtopic.php?f=44&t=3801 “ In this tutorial, the author has given 3 classes. The first, OOoInputStream implements XInputStream and the XSeekable. The OOoInputStream constructor allows us to take a byte array (Our document) and converts it into a stream format that the OpenOffice API can handle. The OOoOutputStream class allows us to do the opposite, convert the OpenOffice stream back into a byte array. The third class provided gives us an example of converting an odt (OpenOffice native document format) document into a PDF document. It might be a worth while exercise to try to get this example working before continuing. In the mean time, add the OOoInputStream and OOoOutputStream classes to your project and delete the OpenOfficeWrapper.java file. We won't be needing it. Right Click the com.sun.OpenOffice package and select “New/Java Class...”. Give this class the name “populateTemplate” and accept all other defaults and click “Finish”. Replace the code with that supplied in the Source Code section of this document for “populateTemplate.java”. Save and build the project. There are two areas of interest in the source code. The first area is the argument to the call to populateTemplate. public byte[] populateTemplate(OOoInputStream input, OOoOutputStream output, HashMap hm) throws Exception { Here we see that we are providing an OooInputStream, OooOutputStream for the input and output result. The final is a hashmap. This hashmap contains the variable names and values that we are going to populate into the document. The names have to match exactly the names specified in the OpenOffice Document template. For example, for our test template, the following would be used to populate the hashmap. HashMap hm = new HashMap(46); hm.put("Name", "Holger Paffrath"); hm.put("Street", "476 St Kilda Rd"); hm.put("City", "Melbourne"); hm.put("PostCode", "3000"); hm.put("State", "Victoria"); The next area of interest in the source code is how we do the pair matching with what is in the document and what is in the hash map. Then going about setting/replacing the value. Here we are going through the fields in the OpenOffice document. Then we check to see if the field exists in the hashmap. If the field exists, we then replace the value with that stored in the hashmap. while (e.hasMoreElements()) { Any tf = (Any) e.nextElement(); XTextField xtf = (XTextField) tf.getObject(); // get the properties of the field XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xtf); Property[] arrprop = xPropertySet.getPropertySetInfo().getProperties(); try { // for ms-word mailmergefield the fieldcode looks // like: MERGEFIELD FIELD_3 * MERGEFORMAT String fieldName = (String) xPropertySet.getPropertyValue("VariableName"); // Check if the field exists in the hashmap. if (hm.containsKey(fieldName)) { String value = (String) hm.get(fieldName); // set the content of the field xPropertySet.setPropertyValue("Content", value); } } catch (UnknownPropertyException ex) { // Fieldcode property doesn't exist, ignore System.out.println("[===] Field property does not exist - ignore"); } } If you recall from above when we set the variables in the template, there was a number of types of fields that could be added.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    30 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us