Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Phantomjs from javascript, JSP or Java

Hi i am new to phantomjs,

I have generated HTML to PDF by using command. But i want to generate PDF by clicking a button on the page. and call phantomjs by some way to generate my given URL to pdf.

You can also suggest some api that generate generate PDF as HTML with charts and images and can easily integrated with JSP and Servlet.

like image 711
user2439207 Avatar asked Jun 03 '13 04:06

user2439207


1 Answers

I'm assuming that what you want to do is to run the phantomjs executable from within Java code.

You'll need to first know the full path of the command you want to execute, in your case, phantomjs. If you downloaded the zip, this is the directory to which you unzipped the file in, where you see the phantomjs.exe executable. If you downloaded it through package manager, to find out the full path run from a terminal:

which phantomjs

Which will display something like

/usr/bin/phantomjs

Once you have that, you'll have to use the Runtime class, which, among other things, lets you run commands directly on the OS using exec. What you run, will then be handled as a Process which you can use to read the output of the command from.

A quick example without any of the Exception handling that you SHOULD be doing.

    Process process = Runtime.getRuntime().exec("/usr/bin/phantomjs myscript.js");
    int exitStatus = process.waitFor();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader (process.getInputStream()));

    String currentLine=null;
    StringBuilder stringBuilder = new StringBuilder(exitStatus==0?"SUCCESS:":"ERROR:");
    currentLine= bufferedReader.readLine();
    while(currentLine !=null)
    {
        stringBuilder.append(currentLine);
        currentLine = bufferedReader.readLine();
    }
    System.out.println(stringBuilder.toString());

Make sure to do proper error handling, as you are creating process external to the JVM, which the JVM doesn't exactly control, and could create issues to the rest of your program if you don't manage errors well.

like image 165
chamakits Avatar answered Oct 08 '22 03:10

chamakits