繁体   English   中英

如何使用Javascript在网页的iframe中预览从外部API生成的PDF文件?

[英]How can I preview a PDF file generated from an external API in an iframe of my webpage, using Javascript?

我一直在尝试在线查找示例,其中外部API返回了PDF(作为响应发送的文件,其中Content-Type的响应头设置为application / pdf),然后在JS中处理该文件并显示在嵌入式div / iframe中。

我一直在尝试使用PDF.js或PDFObject查找示例,但我所能找到的全部使用服务器上托管的pdf文件的直接路径。 我需要在客户端执行此操作,并且只能使用API​​检索文件。

抱歉,如果在某处已对此做出回应,但找不到与我的要求相符的内容,希望我对它的描述足够好!

//Pseudo code of what I'd like to achieve
$.get('http.service.com/getPDF', function(data) {
    var pdfString = changeDataToPDFString(data);

    magicLibrary.previewPDF(pdfString, $('#container_pdf'));
}

对于那些偶然发现此问题的人,这是我使用RequireJS和PDFJS的非常具体的解决方案。

     changeDataToPDFString: function(file) {
         var base64ToUint8Array = function(base64) {
            var raw = atob(base64),
                uint8Array = new Uint8Array(raw.length);

            for (var i = 0; i < raw.length; i++) {
                uint8Array[i] = raw.charCodeAt(i);
            }

            return uint8Array;
         },
         base64Data = file.split(',')[1],
         pdfData = base64ToUint8Array(base64Data);

         return pdfData;
    },
    renderPDF: function(file, container) {
        var self = this,
            pdfData = self.changeDataToPDFString(file);

        require(['pdfjs-dist/build/pdf'], function(app){
            var iframe;

            if(container.find('iframe').length) {
                iframe = container.find('iframe')[0];
                iframe.contentWindow.PDFViewerApplication.open(pdfData);
            }
            else {
                iframe = $('<iframe src="js/lib/pdfjs/web/viewer.html" style="width: 100%; height: 700px;" allowfullscreen="" webkitallowfullscreen=""></iframe>')[0];
                iframe.onload = function() {
                    iframe.contentWindow.PDFViewerApplication.open(pdfData);
                }
                container.append(iframe);
            }
        });
    }

暂无
暂无

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

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