渲染页面时,无法加载外部资源

时间:2014-04-03 14:08:29

标签: node.js pdf-generation phantomjs

我目前正在尝试通过Node&amp ;;从HTML页面生成PDF文档。 PhantomJS。

如果我的页面包含本地资源,或者只包含静态内容,则可以正常工作:

<!doctype html>
<html>
    <head>
        <meta charset="UTF-8" />
        <link rel="StyleSheet" media="screen" href="./style.css" />
        <link rel="StyleSheet" media="print" href="./print.css" />
    </head>
    <body>
        <h1>The title</h1>
        <p>hai <span class="foo">lol <span class="bar">I'm generating</span> a pdf</span> !</p>
        <p class="centre"><img src="http://www.gratuit-en-ligne.com/telecharger-gratuit-en-ligne/telecharger-image-wallpaper-gratuit/image-wallpaper-animaux/img/images/image-wallpaper-animaux-autruche.jpg" /></p>
        <canvas id="test_canvas" width="200px" height="100px"/>

        <script>
            setTimeout(function () {
                var ctx = document.getElementById('test_canvas').getContext('2d');

                ctx.fillStyle = '#FF0000';
                ctx.fillRect(0, 0, 150, 75);
            }, 1000);

            setTimeout(function () {
                evt = document.createEvent('CustomEvent');
                evt.initEvent('pdfTrigger', true, false);

                document.dispatchEvent(evt);
            }, 3000);
        </script>
    </body>
</html>

所以在这里,图像被正确渲染,样式表也被正确渲染。但是,如果我从远处的图像或远程脚本(以//开头,http://https://添加包含,即使它指向我的本地环境),内容未加载:

<!doctype html>
<html>
    <head>
        <meta charset="UTF-8" />
        <link rel="StyleSheet" media="screen" href="./style.css" />
        <link rel="StyleSheet" media="print" href="./print.css" />
    </head>
    <body>
        <h1>The title</h1>
        <p>hai <span class="foo">lol <span class="bar">I'm generating</span> a pdf</span> !</p>
        <p class="centre"><img src="http://upload.wikimedia.org/wikipedia/commons/7/7c/Ostrich,_mouth_open.jpg" /></p>

        <script>
            setTimeout(function () {
                evt = document.createEvent('CustomEvent');
                evt.initEvent('pdfTrigger', true, false);

                document.dispatchEvent(evt);
            }, 3000);
        </script>
    </body>
</html>

不渲染图像;如果我尝试使用来自cdn和jQuery代码的jQuery包含(比如通过$(document).trigger('pdfTrigger')触发事件),它会显示ReferenceError: Can't find variable: $,因此事件永远不会被触发。如果我将它包含在我的html文件中的本地资源(如<script src="./jquery.min.css"></script>)上,则错误消失但事件永远不会被触发...

以下是我使用的幻像脚本:

/**
 * Render a PDF from an HTML file
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 * Adapted from PhantomJs' example "rasterize.js"
 */

var orientation = 'portrait',
    system = require('system'),
    args = system.args.slice(1);

if (args.length < 2 || args.length > 3) {
    system.stderr.writeLine('Usage: rasterize.js source output [orientation]');
    system.stderr.writeLine('   source : html source to put in the pdf');
    system.stderr.writeLine('   output : output when the pdf will be written');
    system.stderr.writeLine('   orientation : document orientation (either portrait or landscape');

    phantom.exit((args.length === 1 & args[0] === '--help') ? 0 : 1);
}

if (typeof args[2] !== 'undefined') {
    if (-1 === ['portrait', 'landscape'].indexOf(args[2])) {
        system.stderr.writeLine('Invalid argument for [orientation]');
        system.stderr.write('Expected either "portrait", either "landscape" ; got "' + args[2] + '"');

        phantom.exit(1);
    }

    orientation = args[2];
}

var page = require('webpage').create(),
    identifier = '___RENDER____';

page.paperSize = { format: 'A4', orientation: orientation, margin: '1cm' };

page.onInitialized = function() {
    page.evaluate(function(identifier) {
        document.addEventListener('pdfTrigger', function () {
            console.log(identifier);
        }, false);
    }, identifier);
};

page.onError = function (msg, trace) {
    system.stderr.writeLine(msg);

    trace.forEach(function(item) {
        system.stderr.writeLine('   ' + item.file + ':' + item.line);
    });

    phantom.exit(1);
}

page.onConsoleMessage = function (msg) {
    console.log(msg);

    if (msg !== identifier) {
        return;
    }

    page.render(args[1], { format: 'pdf' });
    phantom.exit(0);
}

page.open(args[0], function (status) {
    if (status !== 'success') {
        system.stderr.write('Unable to load the file "' + args[0] + '"');
        phantom.exit(1);
    }
});

要启动我的脚本,请使用以下命令:phantomjs rasterize.pdf test.html test.pdf

总结一下,当我在Phantom中尝试渲染它时,我似乎无法从html加载任何外部内容,并且无法识别jQuery(可能还有其他一些脚本?)

有什么想法吗?如果需要更精确,请不要犹豫。

1 个答案:

答案 0 :(得分:1)

变化:

setTimeout(function () {
    evt = document.createEvent('CustomEvent');
    evt.initEvent('pdfTrigger', true, false);

    document.dispatchEvent(evt);
}, 3000);

要:

window.onload = function () {
    evt = document.createEvent('CustomEvent');
    evt.initEvent('pdfTrigger', true, false);

    document.dispatchEvent(evt);
};

它失败的原因是因为该图像非常大,并且在图像被正确下载之前触发了pdf事件。使用window.onload是可靠的,因为只有在加载了所有页面资源时才会运行onload事件。

相关问题