I've been struggling with this issue for several days now. Despite searching through many threads on Stackoverflow, I couldn't find a solution that worked for me.
Below is the Web API code meant to return a simple PDF file:
[HttpGet("pdf/{id}")]
public async Task<IActionResult> GetOrderAsPDF([FromRoute] int id)
{
MemoryStream ms = new MemoryStream();
PdfWriter writer = new PdfWriter(ms);
PdfDocument pdf = new PdfDocument(writer);
writer.SetCloseStream(false);
Document document = new Document(pdf);
Paragraph header = new Paragraph("HEADER")
.SetTextAlignment(TextAlignment.CENTER)
.SetFontSize(20);
document.Add(header);
document.Close();
ms.Position = 0;
return File(ms, "application/pdf", "test.pdf");
}
service.ts
async getOrderPDF(id):Promise<Blob>{
const url = `${this.baseUrl}/orders/pdf/${id}`;
const key: string = await this.getKey();
console.log('key:', key);
let headers = new HttpHeaders();
headers = headers.append('Authorization', [key]);
return this.http.get(url, {responseType: 'blob', headers: headers}).toPromise();
}
component.ts
exportPDF(div_id: string){
this.backhausService.getOrderPDF(2).then(x => {
var newBlob = new Blob([x], { type: "application/pdf" });
console.log(newBlob);
const data = window.URL.createObjectURL(newBlob);
var link = document.createElement('a');
link.href = data;
link.download = "Test.pdf";
link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
});
}
Although the code successfully saves the file as "Test.pdf", I'm unable to open it and receive an error message saying "Failed to Load PDF Document". When inspecting the file with Notepad++, it appears to be a Base64 encoded string.
JVBERi0xLjcKJeLjz9MKNSAwIG9iago8PC9GaWx0ZXI.... (Base64 encoded content)
Any ideas on what might be causing this issue?
UPDATE
Here's a screenshot of the response from the API call in Chrome Dev Tools: