11

I have a controller which send the response Entity as response to AJAX call which is in byte array form of PDF.

Now I want to show that in browser but nothing works. I tried every suggestion from old Stack Overflow questions, but nothing works.

Here is my response from Spring controller:

     `  %PDF-1.4
       %����
       6 0 obj
  <</Filter/FlateDecode/Length 1983>>stream
  x�� .......... [snip rest of the output]`

Here is my AJAX code:

$(".form").submit(function(e) {
    var form = $(this);
    var url = _contextPath + "pdf/" + id;
    $.ajax({
        type: "GET",
        url: url,
        data: form.serialize(),
        datatype: "application/pdf",
        success: function(data, textStatus, jqXHR)
        {
            console.log(data);
            let pdfWindow = window.open("");
            var bb = btoa(encodeURIComponent((data.replace(/[\u00A0-\u2666]/g, function(c) {
                return '&#' + c.charCodeAt(0) + ';';
            }))));
            console.log(bb);
            var file = new Blob([bb], {type:'application/pdf'});
            console.log(file);
            var fileUrl = URL.createObjectURL(file);
            pdfWindow.document.write("<iframe width='100%' height='100%' src= '"+file+"'></iframe>");
            /*var pdfData = btoa(unescape(encodeURIComponent(data)));
            console.log(pdfData);
            var pdfDataa = atob(pdfData);
            console.log(pdfDataa);*/
           /* var bb = btoa(encodeURIComponent((data.replace(/[\u00A0-\u2666]/g, function(c) {
                return '&#' + c.charCodeAt(0) + ';';
            }))));
            console.log(bb);
            var file = new Blob([bb], {type:'application/pdf'});
            var fileUrl = URL.createObjectURL(file);
            window.open(fileUrl,'', 'height=650,width=840');*/
            //console.log(data);
        //    window.open("data:application/pdf;base64, " + data, '', 'height=650,width=840');
            /*var blob = new Blob( [data], { type: "application/pdf" });
            var fileURL = URL.createObjectURL(blob);
            var win = window.open();
            win.document.write('<iframe src="' + fileURL + '" frameborder="0"' +
                ' style="border:0; top:0px; left:0px; bottom:0px;' +
                ' right:0px; width:100%; height:100%;" allowfullscreen></iframe>')*/
           /* var datauri = 'data:application/pdf;base64,' + Base64.encode(data);
            var win = window.open();
            win.document.write('<iframe src="' + datauri + '" frameborder="0"' +
                ' style="border:0; top:0px; left:0px; bottom:0px;' +
                ' right:0px; width:100%; height:100%;" allowfullscreen></iframe>');*/
            //var base64EncodedStr = btoa(unescape(encodeURIComponent(data)));
            //window.open(data,"_blank","scrollbars=yes,resizable=yes");
            //window.open("data:application/pdf," + encodeURI(data));
           // window.open("data:application/pdf," + escape(data));
            //window.open("data:application/pdf," + base64EncodedStr);
          //  window.open("data:application/octet-stream;charset=utf-16le;base64,"+base64EncodedStr);

          //  let pdfWindow = window.open("")
           //   pdfWindow.document.write("<iframe width='100%' height='100%' src='data:application/pdf;base64, "
           //     + blob+"'></iframe>");
          /*  const byteArray = data;
            const blob = new Blob([byteArray], {type: 'application/pdf'});
            const blobURL = URL.createObjectURL(blob);
            var win = window.open();
            win.document.write('<iframe src="' + blobURL + '" frameborder="0"' +
                ' style="border:0; top:0px; left:0px; bottom:0px;' +
                ' right:0px; width:100%; height:100%;" allowfullscreen></iframe>');*/
           /* var len = data.length;
            var buffer = new ArrayBuffer(len);
            var view = new Uint8Array(buffer);
            for (var i = 0; i < len; i++) {
                view[i] = binary.charCodeAt(i);
            }
            */
            /*var base64EncodedStr = btoa(unescape(encodeURIComponent(data.toString())));
            var pdfData = base64EncodedStr;

            var x = window.open();
            var iframe = x.document.createElement('iframe')
            iframe.width = '100%'
            iframe.height = '100%'
            iframe.frameBorder = 0
            iframe.style = "border: 0"
            iframe.src = "data:application/pdf;base64, " + pdfData
            x.document.body.appendChild(iframe);*/
           // $('.form').unbind('submit').submit();

        }
    });
    e.preventDefault();
});
3
  • It's a GET request? Then in the document <iframe id="frame"></iframe>. Then in your js var url = _contextPath + "pdf/" + id; frame.src = url;. Or even simpler <iframe url="#the_url#"></iframe> if the url is static. Commented Feb 7, 2019 at 7:18
  • form data send from ajax call so i can not directly call the url. theresponse i get is in byte array so i want to show that in browser Commented Feb 7, 2019 at 7:21
  • Why type is set to "GET" then? Well anyway, the easiest would be to directly fetch your resource as Blob (this means overriding jQuery's XHR object's responseType, then you'd just have to set an iframe's src to URL.createObjectURL(XHR.response); Commented Feb 7, 2019 at 7:25

3 Answers 3

16

Found the solution here it is, i was sending byte array from spring controller which is in the form like %PDF-1 %����. So i send base64 encoded string from spring controller and send the base64 encoded string to browser and it works.

javascript code :

var arrrayBuffer = base64ToArrayBuffer(data); //data is the base64 encoded string
function base64ToArrayBuffer(base64) {
    var binaryString = window.atob(base64);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes;
}
var blob = new Blob([arrrayBuffer], {type: "application/pdf"});
var link = window.URL.createObjectURL(blob);
window.open(link,'', 'height=650,width=840');

convert byte array to base64 encoded string in spring controller

String encodedString = Base64.getEncoder().encodeToString(bytearrayofpdf);
Sign up to request clarification or add additional context in comments.

2 Comments

if we don't have access to the server, how do we convert the binary string / byte array to a base64 encoded string in javascript?
You can just download pdf as arraybuffer or even blob stackoverflow.com/a/48086247/4854931
4

You can use PDFObject JavaScript utility to view PDF files in your browser. Just create a div with some id and insert the byte array that you get into that div.

PDFObject.embed(<byte array>, "#pdfObjectViewer");

You need to download the PDFObject library and include it in your project from their site for this to work. Or you can use this CDN.

1 Comment

minor note, its not just <byte array>, you need data:application/pdf;base64,<byte array> as the first parameter
-2

$ajax({type:get,xhr:function(){var xhr = new XMLHttpRequest()if(xhr.readyState ==2){ if(xhr.status ==200){ xhr.responseType =".blob"} else{ xhr.responseType="text" } } } return xhr }, success:function(data){ Cost blob = new Blob([data], {type:"application/pdf"}) cost url=window.URL.createObjectURL(blob) window.open(url)}})

1 Comment

Hi, your answer is unreadable. Please format your code: formatting help. After doing it, we can see if your code addresses the question or not. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.