如何在AngularJS应用程序中预览PDf文件?

时间:2017-04-19 04:04:30

标签: javascript angularjs pdf asp.net-web-api

我正在尝试在AngularJS app中预览pdf文档。

从我的Web API,我发送的是字节

[Route("PdfData")]
        [HttpGet]
        public byte[] GetPdfData()
        {
            BlobService bs = new BlobService();
            var blobPdfContent = bs.PdfRecordsInBytes("Sample.pdf");
            return blobPdfContent;
        }

我的angularJS代码如下

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

    <div ng-app="myApp" ng-controller="myCtrl">


        <embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>

    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', [ '$scope', '$sce','$http',function($scope,$sce,$http) {

            $http.get("http://localhost:67845/PdfData")
            .then(function(response) {
                console.log(response.data);                     
                    $scope.content = $sce.trustAsResourceUrl(response.data);
                }); }]);
    </script>

</body>
</html>

在控制台中,我能够找到字节数据,但没有预览......我缺少什么?

控制台

enter image description here

但浏览器

enter image description here

1 个答案:

答案 0 :(得分:1)

已知MIME类型的base64字符串,如@Endless在Convert Data URI to File then append to FormData所示,您可以将data URI传递给fetch()来电返回{{ 1}}从链接Response.blob()到隐蔽.then()编码到base64。将Blob元素<iframe>设置为从.src返回的文件对象的Blob URL,以URL.createObjectURL() .pdf显示html

document

plnkr http://plnkr.co/edit/WrKRF1hKnN36LZ8e6m11?p=preview

另见Displaying pdf from arraybuffer