Skip to content Skip to sidebar Skip to footer

Pdf Is Corrupted After Reconstructing It Using Url.createobjecturl

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 =

Solution 1:

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);

Post a Comment for "Pdf Is Corrupted After Reconstructing It Using Url.createobjecturl"