【问题标题】:Render HTML to PDF with PhantomJS on DOMContentLoaded/Document Ready在 DOMContentLoaded/Document Ready 上使用 PhantomJS 将 HTML 渲染为 PDF
【发布时间】:2014-05-20 14:27:54
【问题描述】:

我是 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 的 webfonts

欢迎提出任何建议!

谢谢

【问题讨论】:

    标签: javascript node.js pdf phantomjs


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-16
      • 1970-01-01
      • 2011-09-07
      • 2023-04-03
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      相关资源
      最近更新 更多