PDF doc displayed in browser in ASP.NET Core MVC app has blank pages

31 Views Asked by At

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'

1

There are 1 best solutions below

0
Jalpa Panchal On

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 underlying XMLHttpRequest object.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 xhrFields option. Below is the example you could try:

$(document).ready(function () {
     $("#viewPdfBtn").click(function () {
         $.ajax({
             url: '@Url.Action("DisplayDocument", "Document")',
             data: { 'documentID': 'dummyId' },
             method: 'GET',
             xhrFields: {
                 responseType: 'blob'
             },
             success: function (blob, status, xhr) {
                 var url = URL.createObjectURL(blob);
                 window.open(url, '_blank');
             },
             error: function (xhr, status, error) {
                 console.error("Error occurred while downloading PDF", error);
             }

         });
     });
 });

enter image description here