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:
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).
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With