Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDF is blank when downloading using javascript

Tags:

javascript

pdf

I have a web service that returns PDF file content in its response. I want to download this as a pdf file when user clicks the link. The javascript code that I have written in UI is as follows:

$http.get('http://MyPdfFileAPIstreamURl').then(function(response){ var blob=new File([response],'myBill.pdf',{type: "text/pdf"}); var link=document.createElement('a'); link.href=window.URL.createObjectURL(blob); link.download="myBill.pdf"; link.click(); }); 

'response' contains the PDF byte array from servlet outputstream of 'MyPdfFileAPIstreamURl'. And also the stream is not encrypted.

So when I click the link, a PDF file gets downloaded successfully of size around 200KB. But when I open this file, it opens up with blank pages. The starting content of the downloaded pdf file is in the image.

I can't understand what is wrong here. Help !

This is the downloaded pdf file starting contents:

This is the downloaded pdf file starting contents

like image 739
programmer129 Avatar asked Dec 23 '15 12:12

programmer129


People also ask

Why is my PDF blank when I download it?

If the fillable fields in a PDF show as blank after getting filled in, the PDF will need to be printed to a new PDF to resolve this issue. This is typically caused when the PDF is filled using something other than Acrobat (i.e., a web browser or other PDF editing software).

How do I enable PDF download in HTML?

With the use of the <a> tag download attribute, we can download pdf files, images, word files, etc. The download attribute specifies that the target (the file specified in the href attribute) will be downloaded when a user clicks on the hyperlink.

How do I download a PDF instead of Open in JavaScript?

Click “Site Settings” on the right. Scroll down in Site Settings and click “Additional content settings” at the very bottom. In the expanded menu, select “PDF documents.” Toggle on the “Download PDF files instead of automatically opening them in Chrome” option.


1 Answers

solved it via XMLHttpRequest and xhr.responseType = 'arraybuffer'; code:

var xhr = new XMLHttpRequest();     xhr.open('GET', './api/exportdoc/report_'+id, true);     xhr.responseType = 'arraybuffer';     xhr.onload = function(e) {        if (this.status == 200) {           var blob=new Blob([this.response], {type:"application/pdf"});           var link=document.createElement('a');           link.href=window.URL.createObjectURL(blob);           link.download="Report_"+new Date()+".pdf";           link.click();        }     }; xhr.send(); 
like image 162
Alexey G Avatar answered Oct 10 '22 14:10

Alexey G