The Ultimate Java PDF Library SDK

Seamless PDF Integration for Java

Download Trial Purchase

How to run the JPedal PDF to Image Converter on the Red Hat OpenShift Cloud

This tutorial explains how to setup the JPedal PDF to Image Converter on the OpenShift Cloud service with a simple example. It will guide you through how to create a working web application. This application will let you upload a PDF file, convert each page of that file into a PNG file and then will download a zip containing those PNG’s to your computer. It will be using the JPedal-trial.jar which you can download here.

What you will need to have done before you start:

  • Completed my previous tutorial: ‘How to setup the Red Hat OpenShift cloud’ in order to create your OpenShift account, install the needed rhc command line tools, create a local test server, set up a domain and learn how to create and pull a project into the NetBeans IDE.
  • Downloaded the JPedal-trial.jar from here

Create a new project

You will already know how to do this from my previous tutorial but I will quickly remind you how to create a new project and clone that project into NetBeans using the rhc tools we installed. We will create this project in the domain we previously created too.

To create a new project you use the command: rhc app-create PDF2ImageConverter tomcat7 which will create our application on a Tomcat 7 server.

1.createApp

At the end of the output will be some useful information to take note of. The URL from where you will run your application shall be displayed and the ssh key that we will use to clone our project into NetBeans.

2.usefulOutput-coloured

Now that we have the application created we can clone the project into NetBeans. The menus in NetBeans are context sensitive so the clone menu item could be in either in Team -> Remote -> Clone or  Team -> Git -> Clone

cloneProject
cloneProject2

Then you need to enter your ssh into the Repository URL section. NetBeans should detect that your username is part of the ssh you entered and cut and paste that into the username section for you.

In the case that NetBeans does not pick this action up here is an example ssh, username and repository URL to help demonstrate which part of the ssh should go where:
 
SSH: ssh://4386ggfnjdwtgbtrdvbet434@testapp2-idrsolutions.rhcloud.com/~/git/testapp2.git/
Username: 4386ggfnjdwtgbtrdvbet434
URL:  ssh://testapp2-idrsolutions.rhcloud.com/~/git/testapp2.git/
 

* Please make a note of your username as we will need this later to navigate your clouds file system. *

 

3.remoteReposPNG

Then set the private key to the key we created in the previous tutorial e.g. C:\Users\yourUserName\.ssh\id_rsa
Finally click NextNext and Finish and your application should be pulled. You will have to open it from where you saved the project.
 
You should get a project that’s structure resembles this:

4.jpedalProject

At this point you can run your application to ensure it is set up correctly and will run locally. You can do this by right clicking the top-most node of your project and clicking Run. You will be asked to select a server to run your application from. Choose the tomcat server which you should have already had as prerequisite from the previous tutorial and select the option to remember this permanently. Selecting this option will mean you will not have to set the server every time you wish to run your project.

5.setServer

Create index.jsp

Index.jsp lives in the Web Pages directory, which is where files should be placed if you want clients to be able to access them via their web browsers. Index.jsp will display a HTML form on the client’s computer, which will let you select a file and upload it to a servlet. The servlet works on the server’s machine and does all of the heavy work so that the client machine can just sit back and wait for it’s file to be converted.
 
As you can see from the projuct structure image above, there are already some files in the Web Pages. We are not going to use index.html or the images folder so lets delete them. Now rename snoop.jsp to index.jsp and delete the contents as we are going to add a HTML form instead.
 
The form will contain two elements: File and Submit. Your file should be given an ID as “pdfFile”. This is important because later on the servlet will use this ID to extract the file from the form request.
 
The form will post to a servlet called PDF2ImageConverter and we will create that in the next step. 

Your index.jsp file should look like this:

You can test your application again (just right-click and select Run) and your form should appear allowing you to select a file. The convert button will return an error page though as we have not created the servlet yet.

Create the servlet / PDF2ImageConverter

At the end of this tutorial I will post the full code for this class without the majority of my comments. You can use the code as a quick reference to make sure you are on the right track. The needed imports are also included in the bottom example.
 
Your servlet should be created and stored in the Source Packages directory since it is essentially a Java class. To create this right click your Source Packages directory, go to the New menu and select the Other menu item. This will open the New File wizard. Choose from the Web category a Servlet file type. Click Next, name your servlet “PDF2ImageConverter” and click Finish.

selectServletFileType

As you can see servlets have some predefined methods like doPost() and processRequest(). When the servlet receives a request via the post method it’s doPost() method is called. This method calls processRequest() and passes in the HttpServletRequest and a HttpServletResponse. We can get any data that was passed along with the HttpServletRequest e.g. a file and similarly attach data to the HttpServletResponse e.g. HTML.
 
@WebServlet(urlPatterns = {“/yourServletName”}) should already be supplied. It is used to specify that the servlet is available at the specified URL pattern. This is how your index.jsp can locate your servlet when sending the form.
@MultipartConfig needs to be added to tell the servlet to expect requests conforming to the multipart/form-data MIME type (so that requests containing a file can be retrieved).
 

This class has 3 jobs so we will make 3 methods and call them in the processRequest method. We pass the request into getFile() because we need the request in order to extract the file from it. Similarly response is passed into downloadFile() because that method that will carry out the download, which will be put into the response for the client. Below is what your class should look like:

Copy the PDF file to a local file on the server / getFile()

In your servlet we are going to add the first method which will copy the file to the server. You should be aware that different servers have different file systems and clouds structure these servers slightly differently. Usually when uploading static content to Tomcat you can store them in the webapps directory. OpenShift has restricted writing permissions to this directory and so we will be writing the files to another directory on your server.

You may have noticed that I have commented out a line of code above:
//String fileOutputPath = “/var/lib/openshift/yourSshUsername/app-root/data/” + sessionName + “/”;
This is the output path that we are going to use when we deploy to the OpenShift cloud. We want to make sure that it works locally before pushing though so that is why I am currently using a different output path. We will swap the output paths once we know it is working.
 
Each application will have a unique file output path. In the file output path shown above you will need to replace the section yourSshUsername with your actual username. You should have made a note of your SSH username in the first step but if you have forgotten it then you can find it by logging into your web console. Just go to Applications and select your app and its on the right as part of your ssh URL. The username is the bit between the ‘ssh://’ and the ‘@’.

testAppInConsole

Add the JPedal jar to your project

In order to use your jar’s functionality you need to add it to the correct folder, so that the classes can be found when the project is compiled on the server. The folder we need to add it to is: pathToProject/pdf2imageconverter/src/main/webapp/WEB-INF/lib. You will have to create the lib folder and paste your jar into it.

6.addJar

Although this will work on the cloud server, your IDE will flag up errors saying the classes for this jar cannot be found. To fix this we will add a depedency to your pom file (which you can find in your IDE under the project files node).

Scroll down until you come to the <dependencies>…</dependencies> tags and inside them add:

Convert the data into a PNG file / convertPdf2Image()

Now that we have added the jar we create the conversion code. We are using the simplest conversion with no options. We can use the example code from here to help us. This code creates a BufferedImage to hold the created PNG pages. ConvertPagesToImage() takes the byte[] and every page is converted in the for loop. ImageIO then writes the BufferedImage to the file we created earlier.

Download file onto the client’s computer / downloadFile()

We will create the downloadFile() method now. This will return a zipped folder to the client’s browser, which the browser will automatically download. We will do this by creating a byte[] from the zipped content of the output folder. We will carry out this functionality in another method called zipFiles().
 
ZipFiles() will create a byte[] by using a variety of InputStreamsOutputStreams and a buffer. The InputStreams are used when we want to read data in and the OutputStreams are used when we want the data to be written to another object. The buffer is used as a placeholder. We also need an int (length) which will tell the OutputStream how many bytes to read.

Test Locally

You can test your application locally by right-clicking the top most and selecting Clean and Build and then right-clicking again and selecting Run.

RunLocally

A new tab should then open. Once you have selected a file and clicked the convert button, a zipped folder should be downloaded by your browser containing your converted pdf.

localTest

Deploy your application to the cloud

Once you have your application working locally, it is time to deploy this application to the cloud. This is fairly simple to do within the NetBeans IDE. Before we do that though we need to enable the correct output path so comment out your current fileOutputPath and enable the other path that contains your ssh username:

Now to deploy your application we need to commit our code changes and push that to the cloud which will run our application for us. To do this right-click your project’s top-most node and select Git -> commit. Enter a useful message and click commit.

commit

Then you need to push your commit by right-clicking your top-most node (testApp) again and selecting Git -> Remote -> Push to upstream.  

push

Run your application

Your changes could take a few minutes to be retrieved and processed by the server. In your web console the server will show a Building status when it receives changes and a Started status when it is running again. Once your application status has started click the provided link e.g. http://pdf2imageconverter-yourDomain.rhcloud.com/ to run your application.

runApp

Complete PDF2ImageConverter code

IDRSolutions Limited 1999-2016