2014-02-21 41 views
2

我正在尝试使用PhantomJS(版本1.9.7)从HTML文本创建PDF。我写了一个非常简单的脚本(通过错误回调等变得更加复杂)使用PhantomJS呈现HTML和图像

phantom.onError = function(msg, trace) { 
    var msgStack = ['PHANTOM ERROR: ' + msg]; 
    if (trace && trace.length) { 
     msgStack.push('TRACE:'); 
     trace.forEach(function(t) { 
      msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function + ')' : '')); 
     }); 
    } 
    system.stdout.write(msgStack.join('\n')); 
    phantom.exit(1); 
}; 

var page = require('webpage').create(); 
page.viewportSize = { width: 800, height: 600 }; 
page.paperSize = { format: 'A4', orientation: 'portrait', margin: '1cm' }; 
page.onResourceRequested = function(requestData, networkRequest) { 
    console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData)); 
}; 
page.onResourceReceived = function(response) { 
    console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response)); 
}; 
page.onResourceError = function(resourceError) { 
    console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')'); 
    console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString); 
}; 
page.onError = function(msg, trace) { 
    var msgStack = ['ERROR: ' + msg]; 
    if (trace && trace.length) { 
     msgStack.push('TRACE:'); 
     trace.forEach(function(t) { 
      msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : '')); 
     }); 
    } 
    console.error(msgStack.join('\n')); 
}; 

page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>"; 
page.render('tmp.pdf'); 
setTimeout(function() { 
    phantom.exit(); 
}, 5000); 

我设置页面,简单的HTML字符串分配给内容的属性,并将其呈现为PDF。

此脚本不会产生任何输出。

我已经将问题缩小到<img>元素,当删除该元素时,会按预期生成PDF。我可以从回调函数看到图像被请求,接收到响应,并且没有错误报告。我试图渲染到一个也没有输出的PNG。

我探讨了这是一个代理问题的可能性,但raserize.js示例没有任何问题。

回答

8

您必须在页面完全加载时调用渲染。请记住,通过page.openpage.content加载页面始终是异步的。

你的代码改成这样

page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>"; 
setTimeout(function() { 
    page.render('tmp.pdf'); 
    phantom.exit(); 
}, 5000); 
+1

当然!在页面加载所有资源之前调用渲染。我还发现'page.onLoadFinished'回调会比使用'setTimeout'更好。 –