I'm trying to display a PDF doc in the browser, in an ASP.NET Core MVC application. I use an Ajax call to a controller which returns the PDF as a byte array.
The problem is, the document that opens in the browser has blank pages. Can anyone suggest what I'm doing wrong?
The controller:
using Microsoft.AspNetCore.Mvc;
public IActionResult DisplayDocument(string documentID)
{
byte[] pdfBytes = System.IO.File.ReadAllBytes(@"C:\Info\sample1.pdf");
return File(pdfBytes, "application/pdf");
}
And the Ajax call...
$.ajax({
url: '@Url.Action("DisplayDocument", "Document")',
data: { 'documentID': docid },
method: 'GET',
responseType: 'arraybuffer',
success: function (response, status, xhr) {
var blob = new Blob([response], { type: 'application/pdf' });
var url = URL.createObjectURL(blob);
window.open(url,'_blank');
},
error: ...
});
I notice the following:
Original PDF file size: 54Kb
Byte array in the controller: 54641 bytes
FileContentResult returned by the controller: 54641 bytes
response.size in Ajax: 52187 bytes
blob.size: 92736 bytes
blob.type: 'application/pdf'
I would like to share with you that the code you are using to set the response type
responseType: 'arraybuffer'to handle the response as binary data is not supported by jQuery to manipulate the underlyingXMLHttpRequestobject.you are seeing blank which might be because incorrect conversion process when trying to create a Blob from the AJAX response data.To handle the binary data with jQuery's AJAX you could use
xhrFieldsoption. Below is the example you could try: