如何下载和保存PDF文件,该文件在PhantomJS的响应标题中作为附件接收?

问题描述 投票:10回答:1

我正在尝试使用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));
 };

'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"
}

请使用PhantomJS建议解决方案。谢谢!

javascript phantomjs
1个回答
0
投票

我一直在使用一个名为'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);
    });
  }

我认为你在这里遇到麻烦的原因是你要求服务器发送JSON作为响应,而不是blob文件对象。

© www.soinside.com 2019 - 2024. All rights reserved.