package org.simantics.document; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.nio.file.Files; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.osgi.framework.BundleContext; import org.simantics.Simantics; public class PhantomJSDriver { public static File fileRef(String fileName) throws IOException { BundleContext context = Activator.getContext(); IPath path = new Path("/" + fileName); URL libURL = FileLocator.find(context.getBundle(), path, null); URL fileURL = FileLocator.toFileURL(libURL); return new File(URLDecoder.decode(fileURL.getPath(), "UTF-8")); } public static String printCommand(String margin, String url, String outFile) throws IOException { try { File f = fileRef("print.js"); String template = new String(Files.readAllBytes(f.toPath())); template = template.replace("%%url", url); template = template.replace("%%margin", margin); template = template.replace("%%file", outFile.replace("\\", "/")); return template; } catch (IOException e) { return null; } } public static void print(String html, DocumentSettings settings, File output) throws IOException { File htmlFile = Simantics.getTempfile("PhantomJSDriver", "html"); Files.write(htmlFile.toPath(), html.getBytes(Charset.forName("UTF-8"))); String browserUrl = htmlFile.toURI().toURL().toString(); File script = Simantics.getTempfile("PhantomJSDriver", "script"); String margin = "{left:\"" + settings.marginLeft + "mm\", right:\"" + settings.marginRight + "mm\", top:\"" + settings.marginTop + "mm\", bottom:\"" + settings.marginBottom + "mm\"}"; String printCommand = PhantomJSDriver.printCommand(margin, browserUrl, output.getAbsolutePath()); Files.write(script.toPath(), printCommand.getBytes()); PhantomJSDriver.execute(script); } public static boolean execute(File javascript) { try { File filePath = fileRef("phantomjs.exe"); String[] args = { filePath.getAbsolutePath(), javascript.getAbsolutePath() }; Process process = new ProcessBuilder(args).start(); try { InputStream input = process.getInputStream(); InputStreamReader reader = new InputStreamReader(input); //StringBuilder sb = new StringBuilder(); while (true) { try { while (reader.ready()) { int r = reader.read(); } int error = process.exitValue(); reader.close(); return error == 0; } catch (IllegalThreadStateException e) { Thread.sleep(100); } } } finally { process.destroy(); } } catch(IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } }