phantomjs实现html生成pdf
实现比较简单,同时能够实现对页面的完全展示成pdf,但是生成的时间比较长且并发很差,很容易直接挂掉
以下是实现:
1.下载phantomjs-2.1.1-windows并解压到本地路劲
2.实现java代码
/**
* 通过phantomjs实现html生成pdf
* @param url 页面的url 得到html生成pdf
* @param phantomjs 运行
* @param jsFile 处理的js
* @param cookieNname 用户cookie
* @param cookieValue 用户值
* @param renderPath 生成pdf的路劲
* @param domain cookie的url的Host
* @param size pdf的页面大小
*/
public static void creatPDF(String url,String phantomjs,String jsFile,String cookieNname,String cookieValue,String renderPath,String domain,String size){
try {
Runtime rt = Runtime.getRuntime();
String exec = phantomjs + " " + jsFile + " " + url + " " + cookieNname + " " + cookieValue + " " +renderPath + " " + domain + " " + size;
rt.exec(exec);
}catch(Exception ex){
ex.printStackTrace();
}
}
对应jsFile
system = require('system')
address = system.args[1];
var page = require('webpage').create();
var url = address;
var name = system.args[2];
var value = system.args[3];
var warrantyCard = system.args[4];
var size = system.args[6].split('*');
var dpi = 72.0, dpcm = dpi/2.54;
var widthCm = size[0], heightCm = size[1]; // A4
//page.viewportSize = { width: Math.round(widthCm * dpcm), height: Math.round(heightCm * dpcm) };
page.paperSize = {width: widthCm+'cm', height: heightCm+'cm', orientation: 'portrait', margin: '0.4cm' };
page.settings.dpi = dpi;
page.settings.loadImages = true;
page.settings.resourceTimeout = 30*1000; // 5 seconds
page.onResourceTimeout = function(e) {
phantom.exit(1);
};
phantom.addCookie({
'name' : name, /* required property */
'value' : value,
'domain' : 'www.baidu.com' //Host:www.baidu.com
});
page.open(url, function (status) {
window.setTimeout(function () {
page.clipRect = { top: 0, left: 200, width: 400, height: 300 }
page.render(warrantyCard); //截图
console.log(page.content);
phantom.exit();
}, 3000);
});
关于生成的pdf规定A4 但是html页面过大问题 ,pdf只能展示页面的一部分宽度 可以在html中添加css zoom:0.7 按情况给百分比