I am requesting an invoice in my nestjs backend from the lexoffice API which returns the file as binary value. Now I want to send it to my angular client but i Am struggling hard with it. The best managed to is that it actually downloads a file, opens a new tab with the document but it displays an error that the pdf failed to load.
My Route in my API:
@Get('invoice/:id')
async downloadInvoice(@Res() res, @Req() req, @Param('id') id: string): Promise<any> {
const resDocFiledId = await this.http.get('https://api.lexoffice.io/v1/invoices/' + id + '/document',
{headers: {Authorization: 'Bearer ' + ServerConstants.lexOfficeApiKey}}).toPromise();
const fileRes = await this.http.get('https://api.lexoffice.io/v1/files/' + resDocFiledId.data.documentFileId,
{
headers: {
Authorization: 'Bearer ' + ServerConstants.lexOfficeApiKey
},
}).toPromise();
res.set({
'Content-Type': 'application/pdf',
'Content-Length': fileRes.headers['content-length'],
});
// fileRes.data is the binary value
res.end(fileRes.data);
}
fileRes.data looks something like this when I log it:
JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9DcmVhdG9yIChDaHJvbWl1bSkKL1Byb2R1Y2VyIChTa2lhL1BERiBtODYpCi9DcmVhdGlvbkRhdGUgKEQ6MjAyMDExMTAyMzMzNTcrMDAnMDAnKQovTW9kRGF0ZSAoRDoyMDIwMTExMDIzMzM1NyswMCcwMCcpPj4KZW5kb2JqCjMgMCBvYmoKPDwvY2EgMQovQk0gL05vcm1hbD4+CmVuZG9iago2IDAgb2JqCjw8L0ZpbHRlciAvRmxhdGVEZWNvZGUKL0xlbmd0aCAxO ... much longer ofcourse
The request in angular:
downloadLexFile(id: string): Observable<any> {
return this.http.get<any>((isDevMode() ? ClientConstants.devServerUrl : ClientConstants.serverUrl) + '/api/shop-data/invoice/' + id, {
headers: {authorization: 'Bearer ' + this.clientAuth.getToken()},
responseType: 'blob',
observe: 'response'
});
}
and thats how I handle the request after its done:
async downloadInvoice(id: string, filename: string): Promise<void> {
const data = (await this.hdap.downloadLexFile(id).toPromise()).body;
const downloadURL = window.URL.createObjectURL(data);
const link = document.createElement('a');
link.target = '_blank';
link.href = downloadURL;
link.download = filename;
link.click();
}