Home > Software engineering >  .NET Web API Serve PDF File
.NET Web API Serve PDF File

Time:11-18

I am trying to serve a PDF file as a ContentResult in my web API. I have tried to return the PDF payload as an <iframe> and as an <object>. However, the base64 encoded data string is too long I believe and neither one loads the PDF file. I want to return a PDF file without forcing users to download it as a separate file and open it in a PDF viewer and instead user the browser's default PDF viewer, hence the <iframe>.

The default from what I gather is 2k characters or 2MB.

The following is my code for return the ContentResult:

return new ContentResult
{
  ContentType = "text/html",
  StatusCode = (int)HttpStatusCode.OK,

  // <iframe> version
  Content = $"<iframe title='PDF Viewer Frame' src='{{data:application/pdf;base64,{myFile}}}' height='600px' width='100%'/>"

  // <object> version
  Content = $"<object type='application/pdf' data='data:application/pdf;base64,{myFile}' height='600' width='600'><object/>"
};

I am not sure if this is the best approach to serving a PDF by API call or if there is a better way.

Thanks for the help!

CodePudding user response:

I was working with React and had a syntax error when I moved the call over to my API. The following should work and there was no issue.

return new ContentResult
{
  ContentType = "text/html",
  StatusCode = (int)HttpStatusCode.OK,

  // <iframe> version
  Content = $"<iframe title='PDF Viewer Frame' src='data:application/pdf;base64,{myFile}' height='600px' width='100%'/>"

  // <object> version
  Content = $"<object type='application/pdf' data='data:application/pdf;base64,{myFile}' height='600' width='600'><object/>"
};

CodePudding user response:

If it possible use FileContentResult instead ContentResult

//read file to byte array, by example from disk
var fileBytes=File.ReadAllBytes(youFileName);

return new FileContentResult(fileBytes, "application/octet-stream") { FileDownloadName = "fileName" };

or

// inline
Response.Headers.Add("Content-Disposition", "inline");
return File(fileBytes, "application/pdf");
  • Related