How to download and save a PDF file received as an attachment in the response header in PhantomJS?

I am trying to download a PDF file using PhantomJS. A direct URL to download this PDF does not exist, as it calls some internal JavaScript function when I click the submit button.

Here is the code that I use to download the PDF file:

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' is the identifier of the item for the submit button. The problem here is that although I get the answer (inside the onResourceReceived ) in JSON format, but I cannot save the attachment as some kind of PDF file.

When I run the above code, I get the following output as a JSON string:

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

Please offer solutions using only PhantomJS. Thanks!

+10
javascript phantomjs
source share
1 answer

I used the html-pdf package (which uses PhantomJS backstage) to create .pdf files (using ejs templates). Hopefully the method I used will give you some recommendations.

I am using Angular, but this should relate to what you are doing. The method I used receives a response from the server in the form of a blob and creates a new Blob instance, and then uploads the created PDF file to the browser using a plug-in (which should exist for your chosen environment):

  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); }); } 

I think the reason you are having problems is because you are asking the server to send you JSON as a response, not a blob file object.

0
source share

All Articles