【问题标题】:How to get AngularJS BLOB to Download PDF?如何让 AngularJS BLOB 下载 PDF?
【发布时间】:2016-05-14 08:01:52
【问题描述】:

大家好,我是使用 AngularJS 开发的新手,我正在尝试弄清楚如何使用 BLOB 将 PDF 本地下载到机器上。我已经让它与 JSON 一起工作,现在我需要一个 PDF。我已经写了一些代码,但它似乎没有工作。

html

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .center {
            position: absolute;
            left: 50%;
            bottom: 50%;
        }

        .btn-purple {
            background-color: rgb(97, 34, 115);
            width: 100px;
        }

    </style>
    <meta charset="UTF-8">
    <title></title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
          integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>


<body>
<div class="center" ng-controller="jsonController" ng-app="app">
    <a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
        <button type="button" class="btn btn-purple">{{fileName}}</button>
    </a>
</div>

<div class="center" ng-controller="pdfController" ng-app="app">
    <a style="color: white;" ng-href="{{ fileUrl }}" download="{{fileName}}">
        <button type="button" class="btn btn-purple">{{fileName}}</button>
    </a>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript-canvas-to-blob/3.1.0/js/canvas-to-blob.js"></script>
<script src="app.js"></script>
</body>
</html>

controller.js

var app = angular.module('app', []);

app.config(['$compileProvider', function ($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
}]);

app.controller('jsonController', function ($scope, $window, $http, $log) {
    $http.get('data.json')
        .success(function (info) {
            var data = angular.toJson(info, true);
            data = data.replace(/\n/g, "\r\n")
            console.log(data)
            var blob = new Blob([data], {type: "octet/stream"}),
                url = $window.URL || $window.webkitURL;
            $scope.fileUrl = url.createObjectURL(blob);
            $scope.schemaName = "test"
            $scope.fileName = $scope.schemaName + ".json"
        })
});
app.controller("pdfController", function ($scope, $http, $log, $sce) {
    $http.get('data.json' + $stateParams.id,
        {responseType: 'arraybuffer'})
        .success(function (response) {
            var file = new Blob([(response)], {type: 'application/pdf'});
            var fileURL = URL.createObjectURL(file);
            $scope.content = $sce.trustAsResourceUrl(fileURL);
        });
});

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    可能的尝试-

    HTML:

    <button ng-click="downloadPdf()" >Download PDF</button>
    

    JS 控制器:

    'use strict';
    var app = angular.module('app')
        .controller('ctrl', function ($scope, MathServicePDF) {
            $scope.downloadPdf = function () {
                var fileName = "file_name.pdf";
                var a = document.createElement("a");
                document.body.appendChild(a);
                ServicePDF.downloadPdf().then(function (result) {
                    var file = new Blob([result.data], {type: 'application/pdf'});
                    var fileURL = window.URL.createObjectURL(file);
                    a.href = fileURL;
                    a.download = fileName;
                    a.click();
                });
            };
    });
    

    JS 服务:

    app.factory('ServicePDF', function ($http) {
            return {
                downloadPdf: function () {
                return $http.get('api/my-pdf', { responseType: 'arraybuffer' }).then(function (response) {
                    return response;
                });
            }
        };
    });
    

    乐于助人!

    【讨论】:

    • 嗨!是否有必要删除那个虚拟的“a”标签后缀?如果是,它有多重要?
    【解决方案2】:

    上使用大文件(> 1.5 GB)进行测试
    • 火狐56.0
    • Safari 11.0

    在您的角度控制器中使用以下内容:

    $scope.download = function() {
     $http({
       method: 'GET',
       url: fileResourceUrl,
       responseType: 'blob'
     }).then(function(response) {
       var blob = response.data;
       startBlobDownload(blob, "largedoc.pdf")
     });
    
    };
    
    function startBlobDownload(dataBlob, suggestedFileName) {
       if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          // for IE
          window.navigator.msSaveOrOpenBlob(dataBlob, suggestedFileName);
       } else {
          // for Non-IE (chrome, firefox etc.)
          var urlObject = URL.createObjectURL(dataBlob);
    
          var downloadLink = angular.element('<a>Download</a>');
          downloadLink.css('display','none');
          downloadLink.attr('href', urlObject);
          downloadLink.attr('download', suggestedFileName);
          angular.element(document.body).append(downloadLink);
          downloadLink[0].click();
    
          // cleanup
          downloadLink.remove();
          URL.revokeObjectURL(urlObject);
      }
    }
    

    【讨论】:

      【解决方案3】:

      将您的 responseType 从 responseType: 'arraybuffer' 更改为 给responseType: 'blob'

      【讨论】:

        【解决方案4】:

        在你的控制器 PHP 中

           return $pdf->stream();
        

        在你的控制器 AngularJS 中

        $http.post('generate', {
            dateStart:  $scope.ds,
            dateEnd:    $scope.de
        }, 
        {
          responseType: 'arraybuffer'
        }).then(function success(response) {
        
          var blob = new Blob([response.data], { type: "application/pdf"});
          saveAs(blob, "filename.pdf");
        
        }, function error(error) {
            $scope.recordErrors(error);
        });
        

        【讨论】:

        • 你确定OP使用php吗?
        【解决方案5】:

        在使用 mpdf 时,此代码在 angular 9 Yii2 中为我工作

        this._gService.download_post(`controller/action`, postData).pipe(takeUntil(this._unsubscribeAll)).subscribe(result => {
        
          const fileURL = URL.createObjectURL(result);
        
          // Direct print preview
        
          // const iframe = document.createElement('iframe');
          // iframe.style.display = 'none';
          // iframe.src = fileURL;
          // document.body.appendChild(iframe);
          // iframe.contentWindow.print();
        
          // Direct Download
        
          const fileName = 'Patient Report';
          const a = document.createElement('a');
          document.body.appendChild(a);
          a.href = fileURL;
          a.download = fileName;
          a.click();
        
        
        }, error => {
           // show error message
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-22
          • 2022-11-02
          • 2021-11-19
          • 1970-01-01
          • 2019-04-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多