Question
In Angular, I need to open a PDF in a new tab and allow the user to download it with a specific name (Example.pdf). The code below downloads the PDF however doesn't open a new tab (target=_blank
is not working). Any ideas how to fix this?
`show(blob){
var fileURL: any = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = fileURL;
a.target = '_blank';
a.download = "Example.pdf";
a.click();
}`
Answer
I solved it using the method below if anyone is interested in a different method.
Service code:
`fetchDocument(fileUrl) {
//pass document url to the service
return this.http.post(
`http://localhost:3000/mydocuments/${fileUrl}`,
{},
{
responseType: 'arraybuffer',
}
);
}`
In your component ts file:
`downloadPDF(content) {
//make a call to the service passing in document url
this.service.fetchDocument(fileUrl)
.subscribe(
(response: any) => {
let array = new Uint8Array(response);
//service returns an array buffer so convert array buffer to blob
let file = new Blob([array], { type: 'application/pdf' });
let fileURL = URL.createObjectURL(file);
window.open(fileURL);
},
(err) => {
console.error(err);
}
);
}`
This answer was originally posted on Stack Overflow. You can find the full discussion here