官方网站:http://phantomjs.org(主要参考官方网站)
Phantom JS是一个服务器端的 JavaScript API 的 WebKit。其支持各种Web标准: DOM 处理, CSS 选择器, JSON, Canvas, 和 SVG,其功能很强大,这里主要是讲一个html转换pdf的demo,也只是Phantom JS的冰山一角。
1.下载Phantom JS安装程序(支持windows,mac os x,linux),目前版本是2.0
2.Phantom JS是通过命令行来执行所有相关的操作,如下代码是将一个网站转化成pdf文件输出
Runtime runtime=Runtime.getRuntime(); String phant_path=PropKit.use("url.properties").get("PHANTOMJS_PATH");//phantomjs的安装路径 //程序执行命令,分为四部分(1.执行程序路径,2.相关功能的js文件(这里是pdf的convert), // 3.html文件的源文件,4.转换后的pdf文件) String command=phant_path+"/bin/phantomjs.exe " + phant_path+"/examples/rasterize.js "+" " +"http://www.oicqzone.com"+" "+"e://test.pdf"; Process process=runtime.exec(command); try { process.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); }
rasterize.js
var page = require('webpage').create(), system = require('system'), address, output, size; if (system.args.length < 3 || system.args.length > 5) { console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]'); console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"'); phantom.exit(1); } else { address = system.args[1]; output = system.args[2]; page.viewportSize = { width: 600, height: 600 }; if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") { size = system.args[3].split('*'); page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' } : { format: system.args[3], orientation: 'portrait', margin: '1cm' }; } if (system.args.length > 4) { page.zoomFactor = system.args[4]; } page.open(address, function (status) { if (status !== 'success') { console.log('Unable to load the address!'); phantom.exit(); } else { window.setTimeout(function () { page.render(output); phantom.exit(); }); } }); }
这是转换PDF的一个例子而已,如果要实行web端导出功能还需html模板,freemarker工具进行html的生成才能进行转换。