phantomjs【html转pdf常见问题】

自定义js脚本[轻松解决html转pdf分页问题及pdf最后一大片空白和渲染的pdf出现蓝条问题]

myhtmltopdf.js

var page = require('webpage').create(),
system = require('system'),
address, output, size;
page.viewportSize = {
  width: 2400,
  height: 20000
};
page.paperSize = { 
format: 'A4', //A4 纸张
orientation: 'portrait', 
margin: '0.8cm' 
};
page.zoomFactor = 1;//放大比例
page.settings.loadImages = true;
page.settings.userAgent = 'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36';
address = system.args[1];
output = system.args[2];
console.log(address);
console.log(output);
page.open(address,function(status){
	if(status=='success'){
		  var cookies = page.cookies;
		  console.log('Listing cookies:');
		  for(var i in cookies) {
			console.log(cookies[i].name + '=' + cookies[i].value);
		  }
	
		window.setTimeout(function (){ 
			page.render(output);
			phantom.exit();  
		}, 5000); 
		console.log('success');
	}else{
		console.log('faild');
	}
 
})

1.使用时出现:unload this address 

解决方案:在需要转pdf的html路径最前面加上file:///,如(file:///C:\export\export.html)

2.在windows上面使用可以直接调用phantomjs.exe

   在Linux上面,需要解压phantomjs文件,不能在java命令中直接调用phantomjs所在的路径,否则会报no such dectory or file,解决方案就是配置环境变量或者调用sh脚本,脚本需要做的事就是:获取到Java传来的phantomjs所在的安装路径,切换到phantomjs的位置,执行一条java传过来的命令执行即可,如命令是(phantomjs C:\work\SMC\webRoot\export\phantomjs2.1.1\example\myhtmltopdf.js file:///C:\work\SMC\webRoot\temp\export\export.html C:\work\SMC\webRoot\temp\export\export.pdf)

调用脚本可参照其他文档

3.如果导出来的pdf不全,则可以调整纸张大小(A1\A2\A3\A4)

 

你可能感兴趣的:(javaEE)