1

I currently have a function in the backend that gives me a stream that contains the PDF file I'm trying to open a download dialog from the client side with this pdf attached.

What I couldn't be able to achieve till now is that I return the stream from the back end and from the front end client side I create this:

    fetch(url)
      .then((response) => {
        return response.blob();
      })
      .then((blob) => {
        var blob = new Blob([myFileStream], { type: 'application/pdf' });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName + '.pdf';
        document.body.appendChild(link);
        link.click();
      });

This opens a download dialog and I could download the file. But, it gives me this error: Error Failed to load PDF document.

I know this might be duplicated but I tried some solutions that made me reach the state I'm at now.

What I'm sure of is that I have the correct PDF file as I can save it in the filesystem from the back end and open it manually and I can see the file content correctly.

What I'm not sure of is what is the correct response format that I should form my file into and return it back from the back end to the front end.

  • This solution guided me for an answer: https://stackoverflow.com/questions/53232820/pdf-is-corrupted-after-reconstructing-it-using-url-createobjecturl – Mostafa Hazem Aug 16 '21 at 14:33

1 Answers1

0

The back-end should return the PDF stream with the MIME type set to application/octet-stream.

Personally, though, I'd do away with all the JS/Ajax code, and just put a link to a route handled by a API controller action...

<a href="/api/pdf/123">My PDF</a>

And the controller action...

[HttpGet("{id}")]
public async Task<IActionResult> GetPdf(int id)
{
    var pdf = await GetPdfAsync(id);

    if (null == pdf)
    {
        return NotFound(); // 404
    }

    return File(
        pdf.Stream,
        "application/octet-stream",
        pdf.Filename);
}

Clicking on the link will cause the browser to open a Save As dialog with the filename already filled in.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Zareh
  • 136
  • 6
  • What is GetPdfAsync and what is File? – Mostafa Hazem Aug 17 '21 at 08:30
  • GetPdfAsync method is a sample method that might return an object that contains the PDF content as a Stream, and a property containing the suggested Filename for the PDF. File is a built-in convenience method provided by the Controller class, and it returns a FileResultObject. – Zareh Aug 18 '21 at 02:07