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

问题描述

我是 phantomjs 的新手,

Hi i am new to phantomjs,

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:24
查看更多