2014-05-20 33 views
0

我是phantomjs的新手,並且在將我的網站呈現爲PDF時遇到問題。我可以得到一個簡單的頁面渲染,但是當加載多個圖像/(網頁)字體時,在phantomjs渲染頁面時DOM沒有加載。使用PhantomJS在DOMContentLoaded/Document Ready上將HTML呈現爲PDF

代碼:

page.open(address, function(status) { 
    if(status !== 'success') { 
     console.log('open page: '+address+' failed..'); 
     phantom.exit(0); 
    } 
}); 

page.onLoadFinished = function(status){ 
    if(status !== 'success'){ 
     console.log('load did not finish correctly'); 
     phantom.exit(0); 
    } else { 
     setTimeout(function() { 
      page.render("../path", {format: 'pdf', quality: '100'}); 
      console.log('pdf generated successfully'); 
      phantom.exit(0); 
     }, 5000); 
    } 
}; 

的代碼工作,我只是想等待DOMContentLoaded。

我想什麼都沒有成功

基礎上的解決方案,以等待DOM來加載發現here

page.onInitialized = function() { 
    page.evaluate(function(domContentLoadedMsg) { 
    document.addEventListener('DOMContentLoaded', function() { 
     window.callPhantom('DOMContentLoaded'); 
    }, false); 
    }); 
}; 

page.onCallback = function(data) { 
    page.render("../path", {format: 'pdf', quality: '100'}); 
    phantom.exit(0); 
}; 

page.open(address, function(status) { 
    if(status !== 'success') { 
     console.log('open page: '+address+' failed..'); 
     phantom.exit(0); 
    } 
}); 

這將使得黑色1KB PDF所以由於某種原因,我不能在page.evaluate回調中調用page.render函數。

原因我想包括網絡字體我運行一個custom build of phantomjs

任何建議,歡迎!

感謝

回答

0

不要等到DOMContentLoaded因爲網絡字體不是DOM的一部分,後來被加載。請使用window.onload = function(){ ... };

page.evaluate(function() { 
    window.onload = function() { 
     window.callPhantom('window loaded'); 
    }; 
}); 

此外phantomjs 1.9.7支持WebFonts。你不需要修補和編譯了。