Running Phantomjs from javascript, JSP or Java

Hi, I'm new to phantomjs,

I created HTML to PDF using the command. But I want to create a PDF by clicking a button on the page. and call phantomjs somehow to create my given pdf url.

You can also offer some api that generate PDF as HTML with diagrams and images and can easily integrate with JSP and Servlet.

+6
source share
2 answers

I assume that you want to run the phantomjs executable from Java code.

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

which phantomjs 

Something like

 /usr/bin/phantomjs 

After that, you will need to use the Runtime class, which, among other things, allows you to run commands directly on the OS using exec. What you run will be treated as a Process , which you can use to read the output of the command.

A quick example without any exception handling that you MUST do.

  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()); 

Be sure to do the correct error handling, as you are creating an external interface for the JVM that the JVM does not precisely control, and can cause problems for the rest of your program if you cope with errors poorly.

+22
source

Of the phantom releases of version 1.8, Ghost Driver, an implementation of WebDriver Wire Protocol, is available.

This allows you to run phantomjs as a remote server that supports http communication with it.

$ phantomjs --webdriver=PORT

This simplifies integration with any programming language.

See here for more details.

+2
source

Source: https://habr.com/ru/post/946375/


All Articles