2

I'm trying to pass a PDF file from the server and display it inside the browser, but the output comes out corrupted.

var blob = atob(data.Package);

console.log(blob);

var file = new Blob([blob], { type: "application/pdf" });

const fileURL = URL.createObjectURL(file);

window.open(fileURL);

Console log outputs something that appears to be correct PDF (just the beginning of output):

enter image description here

I'm saving a copy of the PDF on the server before transfer to make sure it is not corrupt and it works.

URL constructed with URL.createObjectURL(file) seems to be short: blob:http://localhost:61631/ad749684-2992-4311-8b17-f382a7c687be

server side code:

Object doc = Convert.ToBase64String(_Document.DocumentStream.ToArray());
JObject response = new JObject(new JProperty("Package", JObject.FromObject(doc)));
return new AspResponse<Object>(response);
AnKing
  • 1,644
  • 2
  • 23
  • 44
  • What do you mean by "URL constructed with URL.createObjectURL(file) seems to be short"? What do you see when you go to the object url? – jtate Nov 09 '18 at 20:35
  • when the url opens i see a blank page with some artifact in a middle – AnKing Nov 09 '18 at 20:45

1 Answers1

3

It looks like the issue is because you need to convert the PDF data into an actual byte array, then pass that into the Blob constructor. Try this:

function convertToByteArray(input) {
  var sliceSize = 512;
  var bytes = [];

  for (var offset = 0; offset < input.length; offset += sliceSize) {
    var slice = input.slice(offset, offset + sliceSize);

    var byteNumbers = new Array(slice.length);

    for (var i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);

    bytes.push(byteArray);
  }

  return bytes;
}

var blob = atob(data.Package);

console.log(blob);

var file = new Blob(convertToByteArray(blob), { type: "application/pdf" });

const fileURL = URL.createObjectURL(file);

window.open(fileURL);
jtate
  • 2,437
  • 7
  • 27
  • 33