java启动phantomjs_从javascript,JSP或Java运行Phantomjs

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值