I tried opening a PDF file using the window.open(), but the window opens and closes automatically and the file is downloaded like any other file. How to make the pdf file open in new tab? There are no ad blockers installed.
6 Answers
From @barbsan idea, I changed the http headers and received a blob and used that to display the blob as pdf using window.open(). It worked.
Here is my sample code.
In service file
downloadPDF(url): any { const options = { responseType: ResponseContentType.Blob }; return this.http.get(url, options).map( (res) => { return new Blob([res.blob()], { type: 'application/pdf' }); }); } In component file
this.dataService.downloadPDF(url).subscribe(res => { const fileURL = URL.createObjectURL(res); window.open(fileURL, '_blank'); }); 6 Comments
AsGoodAsItGets
Be careful if you're using an ad-blocker extension. Ad-blockers block blob URLs by default. As a result, e.g. in Chrome and Firefox, with the uBlock Origin extension, it would try to open the new window and close it automatically. You can read more about here: stackoverflow.com/questions/51272781/…
AsGoodAsItGets
Also, if you care about this working in IE too, read this: stackoverflow.com/questions/24007073/…
Nagaraja JB
How to set file name while opening file in new tab with above approach?
Pathik Vejani
any idea how to set name of new tab when opening the PDF?
|
you need user the "target="_blank" in the tag ;
exemple: <a target="_blank" href="https://www.google.com/"> </a>
1 Comment
Ruben Helsloot
Hi Hoiama, welcome to StackOverflow! Unfortunately, your answer doesn't address the original question, which was to use explicitly
window.open(). Please make sure to read the question and any answers thoroughly, because it's easy to miss something like this!
window.open('filename','_blank');_blank?