首页 文章

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

提问于
浏览
0

我目前正在尝试通过Node和PhantomJS从HTML页面生成PDF文档 .

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

<!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: $ ,因此事件永远不会被触发 . 如果我将它包含在本地资源(如 <script src="./jquery.min.css"></script> )上的html文件中,则错误消失,但事件永远不会被触发...

这是我正在使用的phantomjs脚本:

/**
 * 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

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

任何的想法 ?如果需要更精确,请不要犹豫 .

1 回答

  • 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 事件 .

相关问题