Ish*_*ain 12 javascript phantomjs
我正在尝试使用PhantomJS下载一些PDF文件.当我单击提交按钮时,没有用于下载PDF的直接URL,因为它调用了一些内部JavaScript函数.
这是我用来下载PDF文件的代码:
page.open(url, function(status){
page.evaluate(function(){
document.getElementById('id').click();
});
});
page.onResourceReceived = function(request){
console.log('Received ' + JSON.stringify(request, undefined, 4));
};
Run Code Online (Sandbox Code Playgroud)
'id'是提交按钮的元素id.这里的问题是,即使我得到响应(内部onResourceReceived回调)作为JSON格式,但我无法将附件保存为某些PDF文件.
当我运行上面的代码时,我得到以下输出作为JSON字符串:
Received {
"contentType": "application/pdf",
"headers": [
// Some other headers.
{
"name": "Content-Type",
"value": "application/pdf"
},
{
"name": "content-disposition",
"value": "attachment; filename=FILENAME.PDF"
},
],
"id": 50,
"redirectURL": null,
"stage": "end",
"status": 200,
"statusText": "OK",
"url": "http://www.someurl.com"
}
Run Code Online (Sandbox Code Playgroud)
请使用PhantomJS建议解决方案.谢谢!
我一直在使用一个名为“html-pdf”的包(它在幕后使用 PhantomJS)来创建 .pdf 文件(使用 ejs 模板)。希望我一直使用的方法能给您一些指导。
我正在使用 Angular,但这应该适用于你正在做的事情。我使用的方法以 Blob 形式接收来自服务器的响应,并创建一个新的 Blob 实例,然后使用插件(该插件应该存在于您选择的框架中)将创建的 .pdf 下载到浏览器:
generatePDF(quote) {
this.http.post(ENV.pdfURL, { quote }, {
// tell the server that response type expected is blob
responseType: 'blob'
}).subscribe((res) => {
// create a new instance of blob using Blob constructor
const blob = new Blob([res], { type: 'application/pdf' });
const filename = `${quote.customerCompany}-${this.getDate()}-${quote.productName}-quote-${quote.selectedDuration / 12}yr.pdf`;
// use a plugin to save the file to the browser
FileSaver.saveAs(blob, filename);
});
}
Run Code Online (Sandbox Code Playgroud)
我认为您遇到问题的原因是您要求服务器向您发送 JSON 作为响应,而不是 blob 文件对象。
| 归档时间: |
|
| 查看次数: |
6228 次 |
| 最近记录: |