Mayur
Mayur

Reputation: 1143

how to open base64 String response from server in external viewer (viewer.html) using pdf.js?

In my application i am sending a path to the server and which returns me a pdf file contents in base64 string. Now i want to show this string in external viewer (viewer.html) using pdf.js. I am doing in this in following way, what wrong am i doing?

var res="JVBERi0xLjUK..."; // Base64 String from response shortened
var pdfData = base64ToUint8Array(res);
window.open('pdfJs/viewer.html?file='+pdfData);

function base64ToUint8Array(base64) {
var raw = atob(base64); //This is a native function that decodes a base64-encoded string.
var uint8Array = new Uint8Array(new ArrayBuffer(raw.length));
for(var i = 0; i < raw.length; i++) {
    uint8Array[i] = raw.charCodeAt(i);
}

return uint8Array;
}

Output i am getting now:

enter image description here

I have gone through some of answers but cant sort it out. So please help me.

Upvotes: 2

Views: 5492

Answers (1)

async5
async5

Reputation: 2691

The Uint8Array cannot be passed via query string. Use PDFViewerApplication.open() method on the opened window, e.g.

var w = window.open('web/viewer.html?file=');
w.addEventListener('load', function () {

  var res="JVBERi0xLjUK..."; // Base64 String from response shortened

  var pdfData = base64ToUint8Array(res);
  w.PDFViewerApplication.open(pdfData);

  function base64ToUint8Array(base64) {
    var raw = atob(base64);
    var uint8Array = new Uint8Array(raw.length);
    for(var i = 0; i < raw.length; i++) {
      uint8Array[i] = raw.charCodeAt(i);
    }
    return uint8Array;
  }
}, true);

Upvotes: 5

Related Questions