Java Html轉pdf實戰 - 簡書年尾手頭沒啥事,干起了打雜工作,最近幫忙解決后端項目里一個html批量轉pdf速度慢的問題,項目里用到的轉換工具是 wkhtmltopdf ,這貨轉單個html還好,批量轉速...https://www.jianshu.com/p/d07bca50daed?from=groupmessage
年尾手頭沒啥事,干起了打雜工作,最近幫忙解決后端項目里一個html批量轉pdf速度慢的問題,項目里用到的轉換工具是 wkhtmltopdf ,這貨轉單個html還好,批量轉速度就慢了。幾經摸索(各種baidu、google......)各種測試后,終于找到個性能不錯的工具 —— phantomjs
Phantomjs安裝
官網地址:PhantomJS - Scriptable Headless Browser
下載地址:Download PhantomJS
選擇合適自己系統的版本,解壓就行,目錄結構如下圖(mac為例)
新建 html2pdf.js 文件,把下面代碼拷進去,文件最好放在phantomjs的bin目錄下
var page = require('webpage').create();
var system = require('system');讀取命令行參數,也就是js文件路徑。
if (system.args.length === 1) {console.log('Usage: loadspeed.js <some URL>');
//這行代碼很重要。凡是結束必須調用。否則phantomjs不會停止phantom.exit();
}
page.settings.loadImages = true; //加載圖片
page.settings.resourceTimeout = 30000;//超過10秒放棄加載
//截圖設置,
//page.viewportSize = {
// width: 1000,
// height: 3000
//};
var address = system.args[1];
page.open(address, function(status) {function checkReadyState() {//等待加載完成將頁面生成pdfsetTimeout(function () {var readyState = page.evaluate(function () {return document.readyState;});if ("complete" === readyState) {page.paperSize = { width:'1500px',height:'2000px',orientation: 'portrait',border: '1cm' };var timestamp = Date.parse(new Date());var pdfname = 'HT_'+timestamp + Math.floor(Math.random()*1000000);var outpathstr = "/Users/zachary/Downloads/phantomjs2/bin/"+pdfname+".pdf";page.render(outpathstr);//console.log就是傳輸回去的內容。console.log("生成成功");console.log("$"+outpathstr+"$");phantom.exit(); } else {checkReadyState();}},1000);}checkReadyState();
});
Phantomjs使用
打開終端,進入phantomjs的bin目錄,執行命令phantomjs html2pdf.js "網址或html文件路徑"
,注意空格
image.png
生成路徑在 html2pdf.js 文件里設置,可以看到bin目錄下生成pdf成功
打開看下效果,相當Nice ! ! !
?