Running Phantomjs from javascript, JSP or Java

2019-01-17 18:51发布

问题:

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.

回答1:

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.



回答2:

From phantomjs release 1.8 is available Ghost Driver, an implementation of WebDriver Wire Protocol.

It allow to start phantomjs as remote server enabling http communication with it.

$ phantomjs --webdriver=PORT

This makes easy integration with whatever programming language

For further details take a look here