简体   繁体   English

如何显示 base64 编码的 pdf?

[英]how to display base64 encoded pdf?

I have to display base64 pdf in new tab.我必须在新标签中显示 base64 pdf。 I am using below code我正在使用下面的代码

 var windo = window.open("", "");  
 var objbuilder = '';
 objbuilder += ('<embed width=\'100%\' height=\'100%\'  src="data:application/pdf;base64,');
 objbuilder += (fileData);
 objbuilder += ('" type="application/pdf" />');
 windo.document.write(objbuilder); 

It is working in FireFox and not working in Chrome and IE.它在 FireFox 中工作,而不在 Chrome 和 IE 中工作。 I even tried with tag, but same output, working in FF but not in Chrome and IE.我什至尝试使用标签,但同样的 output,在 FF 中工作,但在 Chrome 和 IE 中没有。

I look into below JsFiddles, for which are working in FF but not in Chrome,我查看了下面的 JsFiddles,它们在 FF 中工作但不在 Chrome 中,

http://jsfiddle.net/yLx2W/ http://jsfiddle.net/yLx2W/

http://jsfiddle.net/yLx2W/1/ http://jsfiddle.net/yLx2W/1/

My Chrome version is: Version 54.0.2840.99 m我的 Chrome 版本是:版本 54.0.2840.99 m

FireFox Version: 49.0.2 FireFox 版本:49.0.2

Is any one have any idea, please share.有没有人有什么想法,请分享。

Thanks in Advance提前致谢

for those who still can't do it, i found this in someone else answer, but i don't remember who...对于那些仍然无法做到的人,我在其他人的答案中找到了这个,但我不记得是谁......

var objbuilder = '';
objbuilder += ('<object width="100%" height="100%" 
data="data:application/pdf;base64,');
objbuilder += (myBase64string);
objbuilder += ('" type="application/pdf" class="internal">');
objbuilder += ('<embed src="data:application/pdf;base64,');
objbuilder += (myBase64string);
objbuilder += ('" type="application/pdf"  />');
objbuilder += ('</object>');

var win = window.open("#","_blank");
var title = "my tab title";
win.document.write('<html><title>'+ title +'</title><body style="margin-top: 
0px; margin-left: 0px; margin-right: 0px; margin-bottom: 0px;">');
win.document.write(objbuilder);
win.document.write('</body></html>');
layer = jQuery(win.document);

this way we open the pdf in a new tab.这样我们就可以在新标签页中打开 pdf。

It should work with Chrome you can use它应该适用于您可以使用的 Chrome

<iframe src="data:base64...">

<object data="data:base64...">

I've faced the same issue with IE : it's impossible to display a pdf with a base64 string.我在IE 上遇到了同样的问题:无法显示带有base64字符串的 pdf。

I had to generate temporary files on the server to display them with IE he only display existing file by using a path.我不得不在服务器上生成临时文件以使用IE显示它们,他只使用路径显示现有文件

You still can use JS library to display your pdf like PDF.js .您仍然可以使用JS 库来像PDF.js一样显示您的 pdf。

function printPreview(data){
        var type = 'application/pdf';
        let blob = null;
        const blobURL = URL.createObjectURL( pdfBlobConversion(data, 'application/pdf'));
        const theWindow = window.open(blobURL);
        const theDoc = theWindow.document;
        const theScript = document.createElement('script');
        function injectThis() {
            window.print();
        }
        theScript.innerHTML = 'window.onload = ${injectThis.toString()};';
        theDoc.body.appendChild(theScript);
    }
  //converts base64 to blob type for windows
    function pdfBlobConversion(b64Data, contentType) {
          contentType = contentType || '';
          var sliceSize = 512;
          b64Data = b64Data.replace(/^[^,]+,/, '');
          b64Data = b64Data.replace(/\s/g, '');
          var byteCharacters = window.atob(b64Data);
          var byteArrays = [];

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

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

            var byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
          }

          var blob = new Blob(byteArrays, { type: contentType });
          return blob;
        }

pass base64 data to this function and it will show the pdf in new window.将 base64 数据传递给此函数,它将在新窗口中显示 pdf。 This is working in chrome and firefox not in IE.这适用于 chrome 和 firefox 而不是 IE。 Any help Please.任何帮助请。 I want it to work in IE also.我也希望它在 IE 中工作。 Its giving error where I give the bloburl to window.它给出了错误,我将 bloburl 提供给窗口。

When the above answer's do not work due to Size Limitations, you can try this solution, it worked for me when I was trying to convert 16+ page PDFs from Base64 back into a PDF in Chrome.当上述答案由于大小限制而不起作用时,您可以尝试此解决方案,当我尝试将 16 页以上的 PDF 从 Base64 转换回 Chrome 中的 PDF 时,它对我有用。

The fix is to convert the base64 back into Binary, pack it inside of a Blob, and then set the iframe's "src" to a Blob-URI pointing to that blob.解决方法是将 base64 转换回二进制文件,将其打包到 Blob 中,然后将 iframe 的“src”设置为指向该 blob 的 Blob-URI。

var base64 = ("yourBase64StringVariable")
const blob = base64ToBlob( base64, 'application/pdf' );
const url = URL.createObjectURL( blob );
const pdfWindow = window.open("");
pdfWindow.document.write("<iframe width='100%' height='100%' src='" + url + "'></iframe>");

function base64ToBlob( base64, type = "application/octet-stream" ) {
  const binStr = atob( base64 );
  const len = binStr.length;
  const arr = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    arr[ i ] = binStr.charCodeAt( i );
  }
  return new Blob( [ arr ], { type: type } );
}

Original Source of this answer - Open base64 encoded pdf file using javascript.此答案的原始来源 - 使用 javascript 打开 base64 编码的 pdf 文件。 Issue with file size larger than 2 MB 文件大小大于 2 MB 的问题

Here '@Model.binaryDocument' is the base64 data这里 '@Model.binaryDocument' 是 base64 数据

1)By Model 1)按型号

<object>
   <embed id="pdfID" type="text/html" width="1200" height="600" src="data:application/pdf;base64,@Model.binaryDocument" />
</object>

2)By js 2)通过js

  $(document).ready(function () {
    var b64Data = "@Model.binaryDocument";
    var contentType = "application/pdf";
     const blob = b64toBlob(b64Data, contentType);
    const blobUrl = URL.createObjectURL(blob);

    window.location = blobUrl;
  })

const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
    const byteCharacters = atob(b64Data);
    const byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) 
       {
        const slice = byteCharacters.slice(offset, offset + sliceSize);

        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }

    const blob = new Blob(byteArrays, { type: contentType });
    return blob;
}

First solution is better for prevent auto downloading pdf. 第一个解决方案更适合防止自动下载 pdf。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM