【问题标题】:Angular download pdf角下载pdf
【发布时间】:2016-06-23 16:24:12
【问题描述】:

我有从服务器获取 pdf 数据的 angular 函数:

    printDocument: function (bundleId, policyId) {
        var fileName = "test.pdf";
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";

        $resource(baseUrlPrint, {
            bundleId: bundleId,
            policyId: policyId
        }, {
            get: {
                method: 'GET'
            },
            responseType:'arraybuffer',
            cache: true
        }).get().$promise.then(function(result) {
            console.log(result);
            var file = new Blob([result], {type: 'application/pdf'});
            var fileURL = (window.URL || window.webkitURL).createObjectURL(file);
            a.href = fileURL;
            a.download = fileName;
            a.click();
        });
    }

当我检查 result 变量时,我看到字节数组包含 pdf 文件。但是当我在 Notepad++ 中打开这个文件时,我看到没有 pdf 字节数据,只有: [对象对象]。我的 Blob 对象有问题吗?

【问题讨论】:

    标签: angularjs pdf download blob


    【解决方案1】:

    如果 API Rest 检索字节数组,您可以简单地使用这个 js 函数

    (function() {
        'use strict';
    
        angular
            .module('fileUtils')
            .service('DownloadService', DownloadService);
    
        DownloadService.$inject = ['$window'];
    
        function DownloadService($window) { // jshint ignore:line
    
            this.download = function (fileBytes, name, type) {
                var fileName = '';
                if (name) {
                     fileName = name + '.' + type;
                } else {
                     fileName = 'download.' + type;
                }
    
                var byteCharacters = atob(fileBytes);
                var byteNumbers = new Array(byteCharacters.length);
                for (var i = 0; i < byteCharacters.length; i++) {
                    byteNumbers[i] = byteCharacters.charCodeAt(i);
                }
                var byteArray = new Uint8Array(byteNumbers);
    
                var file = new Blob([byteArray], { type: 'application/' + type });
    
                if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveOrOpenBlob(file, fileName);
                } else {
                    //trick to download store a file having its URL
                    var fileURL = URL.createObjectURL(file);
                    var a = document.createElement('a');
                    a.href = fileURL;
                    a.target = '_blank';
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                }
            };
        }
    })();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 2014-03-23
      • 1970-01-01
      • 2021-12-22
      • 2017-02-07
      相关资源
      最近更新 更多