从javascript,JSP或Java运行Phantomjs [英] Running Phantomjs from javascript, JSP or Java

查看:209
本文介绍了从javascript,JSP或Java运行Phantomjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我是phantomjs的新手,

Hi i am new to phantomjs,

我已使用命令生成HTML到PDF。但我想通过单击页面上的按钮生成PDF。并通过某种方式调用phantomjs来生成我的给定URL到pdf。

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.

您还可以建议一些api生成PDF格式的HTML图表和图像,并且可以轻松集成JSP和Servlet。

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

推荐答案

我假设您要做的是从Java代码中运行phantomjs可执行文件。

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

在你的情况下,你需要首先知道你要执行的命令的完整路径phantomjs。如果您下载了zip,则这是您将文件解压缩到的目录,您可以在其中看到phantomjs.exe可执行文件。如果你通过包管理器下载它,找出从终端运行的完整路径:

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

这将显示类似

/usr/bin/phantomjs

一旦你有了,你将不得不使用运行时类,除其他外,它允许您直接运行命令在使用exec的操作系统上。您运行的内容将作为流程处理,您可以用于从中读取命令的输出。

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

确保正确执行错误处理,因为您正在创建JVM的外部进程,即JVM如果你不能很好地管理错误,它就不能完全控制,并且可能会给你的程序的其余部分带来问题。

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.

这篇关于从javascript,JSP或Java运行Phantomjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆