1 |
|
2 | downloadPdf(id: number) { |
3 | this.http.post('/api/documents', { id }) |
4 | .subscribe( |
5 | (base64Pdf: string) => { |
6 | const arrayBuffer = base64ToArrayBuffer(base64Pdf); |
7 | createAndDownloadBlobFile(arrayBuffer, 'testName'); |
8 | }, |
9 | error => console.error(error) |
10 | ) |
11 | } |
12 |
|
13 |
|
14 | export function base64ToArrayBuffer(base64: string) { |
15 | const binaryString = window.atob(base64); |
16 | const bytes = new Uint8Array(binaryString.length); |
17 | return bytes.map((byte, i) => binaryString.charCodeAt(i)); |
18 | } |
19 |
|
20 |
|
21 | createAndDownloadBlobFile(body, filename, extension = 'pdf') { |
22 | const blob = new Blob([body]); |
23 | const fileName = `${filename}.${extension}`; |
24 | if (navigator.msSaveBlob) { |
25 | |
26 | navigator.msSaveBlob(blob, fileName); |
27 | } else { |
28 | const link = document.createElement('a'); |
29 | |
30 | if (link.download !== undefined) { |
31 | const url = URL.createObjectURL(blob); |
32 | link.setAttribute('href', url); |
33 | link.setAttribute('download', fileName); |
34 | link.style.visibility = 'hidden'; |
35 | document.body.appendChild(link); |
36 | link.click(); |
37 | document.body.removeChild(link); |
38 | } |
39 | } |
40 | } |