1 package org.simantics.document;
\r
4 import java.io.IOException;
\r
5 import java.io.InputStream;
\r
6 import java.io.InputStreamReader;
\r
8 import java.net.URLDecoder;
\r
9 import java.nio.charset.Charset;
\r
10 import java.nio.file.Files;
\r
12 import org.eclipse.core.runtime.FileLocator;
\r
13 import org.eclipse.core.runtime.IPath;
\r
14 import org.eclipse.core.runtime.Path;
\r
15 import org.osgi.framework.BundleContext;
\r
16 import org.simantics.Simantics;
\r
18 public class PhantomJSDriver {
\r
20 public static File fileRef(String fileName) throws IOException {
\r
22 BundleContext context = Activator.getContext();
\r
23 IPath path = new Path("/" + fileName);
\r
24 URL libURL = FileLocator.find(context.getBundle(), path, null);
\r
25 URL fileURL = FileLocator.toFileURL(libURL);
\r
26 return new File(URLDecoder.decode(fileURL.getPath(), "UTF-8"));
\r
30 public static String printCommand(String margin, String url, String outFile) throws IOException {
\r
33 File f = fileRef("print.js");
\r
34 String template = new String(Files.readAllBytes(f.toPath()));
\r
35 template = template.replace("%%url", url);
\r
36 template = template.replace("%%margin", margin);
\r
37 template = template.replace("%%file", outFile.replace("\\", "/"));
\r
39 } catch (IOException e) {
\r
45 public static void print(String html, DocumentSettings settings, File output) throws IOException {
\r
47 File htmlFile = Simantics.getTempfile("PhantomJSDriver", "html");
\r
48 Files.write(htmlFile.toPath(), html.getBytes(Charset.forName("UTF-8")));
\r
50 String browserUrl = htmlFile.toURI().toURL().toString();
\r
52 File script = Simantics.getTempfile("PhantomJSDriver", "script");
\r
54 String margin = "{left:\"" + settings.marginLeft + "mm\", right:\"" + settings.marginRight + "mm\", top:\"" + settings.marginTop + "mm\", bottom:\"" + settings.marginBottom + "mm\"}";
\r
56 String printCommand = PhantomJSDriver.printCommand(margin, browserUrl, output.getAbsolutePath());
\r
58 Files.write(script.toPath(), printCommand.getBytes());
\r
59 PhantomJSDriver.execute(script);
\r
63 public static boolean execute(File javascript) {
\r
67 File filePath = fileRef("phantomjs.exe");
\r
69 String[] args = { filePath.getAbsolutePath(),
\r
70 javascript.getAbsolutePath()
\r
72 Process process = new ProcessBuilder(args).start();
\r
74 InputStream input = process.getInputStream();
\r
75 InputStreamReader reader = new InputStreamReader(input);
\r
76 //StringBuilder sb = new StringBuilder();
\r
79 while (reader.ready()) {
\r
80 int r = reader.read();
\r
83 int error = process.exitValue();
\r
88 } catch (IllegalThreadStateException e) {
\r
95 } catch(IOException e) {
\r
96 e.printStackTrace();
\r
97 } catch (InterruptedException e) {
\r
98 e.printStackTrace();
\r