'Downloading PDF from API via Javascript
i am using vue.js and found some good examples how to realize this.
Currently my API is returning a test-pdf:
$snappy = App::make('snappy.pdf');
$html = '<h1>Bill</h1><p>You owe me money, dude.</p>';
return Response(
$snappy->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
Downloading the Content via Postman works well.
I managed the JS-part like this:
export const InvoiceService = {
get(slug) {
return ApiService.get("invoice", slug);
},
downloadPdf(slug) {
return ApiService.get(`pdf/invoice`, slug, {
responseType: 'arraybuffer'
});
}
};
and:
InvoiceService.downloadPdf(invoiceId)
.then(({ data }) => {
let blob = new Blob([data], {
type: "application/pdf"
});
FileSaver.saveAs(blob, "invoice.pdf");
})
.catch(error => {
throw new Error(error);
});
The download works fine but the file downloaded via js seems to be corruped (PDF wont show):

The green marked text is the content of the working pdf.
I think something is messed up with the charset, but i ran out of Ideas :(
Hopefully someone can give me a hint - It drives me nuts :)
Best regards - Alex
Solution 1:[1]
You can use Axios with responseType: 'blob'
// Function that downloads PDF
function download(data) {
const url = URL.createObjectURL(data);
const a = document.createElement('a');
a.download = 'test.pdf';
a.href = url;
a.target = '_self';
a.click();
setTimeout(function () {
// For Firefox it is necessary to delay revoking the ObjectURL
a.remove();
URL.revokeObjectURL(url);
}, 100);
}
// Get data from the API
const response = await axios.get('URL', {
responseType: 'blob', // THIS is very important, because we need Blob object in order to download PDF
});
// Invoke download function
download(response);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GonEbal |

