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