How to Display blob (.pdf) in an AngularJS app

后端 未结 8 1294
逝去的感伤
逝去的感伤 2020-11-22 11:01

I have been trying to display pdf file which I am getting as a blob from a $http.post response. The pdf must be displayed within the app using

相关标签:
8条回答
  • 2020-11-22 11:51

    I faced difficulties using "window.URL" with Opera Browser as it would result to "undefined". Also, with window.URL, the PDF document never opened in Internet Explorer and Microsoft Edge (it would remain waiting forever). I came up with the following solution that works in IE, Edge, Firefox, Chrome and Opera (have not tested with Safari):

    $http.post(postUrl, data, {responseType: 'arraybuffer'})
    .success(success).error(failed);
    
    function success(data) {
       openPDF(data.data, "myPDFdoc.pdf");
    };
    
    function failed(error) {...};
    
    function openPDF(resData, fileName) {
        var ieEDGE = navigator.userAgent.match(/Edge/g);
        var ie = navigator.userAgent.match(/.NET/g); // IE 11+
        var oldIE = navigator.userAgent.match(/MSIE/g); 
    
        var blob = new window.Blob([resData], { type: 'application/pdf' });
    
        if (ie || oldIE || ieEDGE) {
           window.navigator.msSaveBlob(blob, fileName);
        }
        else {
           var reader = new window.FileReader();
           reader.onloadend = function () {
              window.location.href = reader.result;
           };
           reader.readAsDataURL(blob);
        }
    }
    

    Let me know if it helped! :)

    0 讨论(0)
  • 2020-11-22 11:56

    A suggestion of code that I just used in my project using AngularJS v1.7.2

    $http.get('LabelsPDF?ids=' + ids, { responseType: 'arraybuffer' })
                .then(function (response) {
                    var file = new Blob([response.data], { type: 'application/pdf' });
                    var fileURL = URL.createObjectURL(file);
                    $scope.ContentPDF = $sce.trustAsResourceUrl(fileURL);
                });
    
    <embed ng-src="{{ContentPDF}}" type="application/pdf" class="col-xs-12" style="height:100px; text-align:center;" />
    
    0 讨论(0)
提交回复
热议问题