在DOMContentLoaded / Document Ready上使用PhantomJS将HTML渲染为PDF

时间:2014-05-20 14:27:55

标签: javascript node.js pdf phantomjs

我是phantomjs的新手,并且在将我的网站呈现为PDF时遇到问题。我可以得到一个简单的页面渲染,但是当加载多个图像/(web)字体时,当phantomjs呈现页面时,DOM没有加载。

代码:

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

的网络字体

欢迎任何建议!

由于

1 个答案:

答案 0 :(得分:0)

不要等待DOMContentLoaded,因为WebFonts不是DOM的一部分,稍后会加载。而是使用window.onload = function(){ ... };

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

phantomjs 1.9.7也支持WebFonts。您不需要修补和编译了。