【问题标题】:How to show pdf in browser using byte array of pdf in javascript?如何在javascript中使用pdf的字节数组在浏览器中显示pdf?
【发布时间】:2019-02-07 07:04:19
【问题描述】:

我有一个控制器,它发送响应实体作为对 ajax 调用的响应,它是 pdf 的字节数组形式。 现在我想在浏览器中显示它,但没有任何效果。我尝试了旧 stackoverlow 问题的所有建议,但没有任何效果。

这是我来自弹簧控制器的回复

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

这是我的 ajax 代码

 $(".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();
                });

我尝试了所有方法,但我没有工作

【问题讨论】:

  • 这是一个 GET 请求?然后在文档&lt;iframe id="frame"&gt;&lt;/iframe&gt;。然后在你的 js var url = _contextPath + "pdf/" + id; frame.src = url; 中。或者更简单的&lt;iframe url="#the_url#"&gt;&lt;/iframe&gt; 如果网址是静态的。
  • 表单数据从 ajax 调用发送,所以我不能直接调用 url。我得到的响应是字节数组,所以我想在浏览器中显示它
  • 为什么 type 设置为 "GET" 呢?无论如何,最简单的方法是直接将您的资源作为 Blob 获取(这意味着覆盖 jQuery 的 XHR 对象的 responseType,然后您只需将 iframe 的 src 设置为 URL.createObjectURL(XHR.response);
  • 你能告诉我怎么做吗?

标签: javascript jquery ajax


【解决方案1】:

在这里找到了解决方案,我正在从弹簧控制器发送字节数组,其格式类似于 %PDF-1 %����。 所以我从spring控制器发送base64编码字符串并将base64编码字符串发送到浏览器,它可以工作。

javascript代码:

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

在spring控制器中将字节数组转换为base64编码的字符串

String encodedString = Base64.getEncoder().encodeToString(bytearrayofpdf);

【讨论】:

  • 如果我们无权访问服务器,如何在javascript中将二进制字符串/字节数组转换为base64编码的字符串?
  • 您可以将 pdf 下载为 arraybuffer 甚至 blob stackoverflow.com/a/48086247/4854931
【解决方案2】:

您可以使用pdfObject 在浏览器中查看 pdf。只需创建一个带有一些 id 的 div 并将您进入该 div 的字节数组插入。

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

您需要从他们的网站下载 pdfObject 脚本并将其包含在您的项目中才能使用。或者你可以使用这个CDN

【讨论】:

  • 小注意,不只是&lt;byte array&gt;,你需要data:application/pdf;base64,&lt;byte array&gt;作为第一个参数
猜你喜欢
  • 2021-11-21
  • 2015-05-02
  • 2017-12-28
  • 1970-01-01
  • 2014-06-18
  • 2014-08-03
  • 1970-01-01
  • 1970-01-01
  • 2023-02-23
相关资源
最近更新 更多