首页 文章

AngularJS显示从Spring @RestController接收的PDF(byte [])

提问于
浏览
8

我的要求是在表格提交/发布时在我的角度js app中显示(新标签)/下载/嵌入PDF .

我不希望服务器返回生成的PDF的唯一标识符,而是使用$ window服务打开一个新窗口,其中url指向服务器端 endpoints ,该 endpoints 根据唯一标识符返回PDf . 因为我需要动态生成pdf(不存储在文件系统中) .

与此类似的问题AngularJS: Display blob (.pdf) in an angular app但它对我不起作用 .

My controller

angular.module('EvaluationResultsModule').controller('CA_EvaluationResultsCtrl',
    [ '$scope', 'EvaluationResultsService', '$sce', function($scope, EvaluationResultsService, $sce) {

        $scope.showPDF = function() {
            $scope.result = CA_EvaluationResultsService.getEvalutaionResultPDF($scope.evaluationResults);
            $scope.result.$promise.then(function(data) {
                var file = new Blob([data], {
                    type : 'application/pdf'
                });
                var fileURL = URL.createObjectURL(file);
                $scope.pdfContent = $sce.trustAsResourceUrl(fileURL);
            });
        }
    } ]);

My Service

angular.module('EvaluationResultsModule').factory('EvaluationResultsService', function($resource) {
    return $resource('./api/ca/evaluationResults/:dest', {}, {       
        getEvalutaionResultPDF : {
            method : 'GET',
            params : {
                dest : "getPDF"
            },
            responseType : 'arraybuffer',

        }
    });
});

Rest Controller Method

@RequestMapping(value = "/getPDF", method = RequestMethod.GET)
    public byte[] getEvalutaionResultPDF()  {        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Generate PDF using Jasper
        Map<String, Object> model = new HashMap<String, Object>();
        List<User> usersList = null; //populated from Service layer;
        JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(usersList);
        JasperPrint jasperPrint =  jasperPrint = JasperFillManager.fillReport(this.getClass().getClassLoader().getResourceAsStream("A4.jasper"), model, beanColDataSource);
        JasperExportManager.exportReportToPdfStream(jasperPrint, baos);
        return baos.toByteArray();
    }

My response logged in console

response:  Object {data: ArrayBuffer, status: 200, headers: function, config: Object, statusText: "OK"}config: Objectdata: ArrayBufferbyteLength: (...)__proto__: ArrayBufferbyteLength: [Exception: TypeError: Method ArrayBuffer.prototype.byteLength called on incompatible receiver #<ArrayBuffer>]get byteLength: function byteLength() { [native code] }constructor: function ArrayBuffer() { [native code] }slice: function slice() { [native code] }__proto__: Objectheaders: function (name) {resource: Resourcestatus: 200statusText: "OK"__proto__: Object

3 回答

  • 15

    我使用这个代码,它适用于我:

    REST控制器:

    @RequestMapping(value = "/api/reports/pdf", method = RequestMethod.GET)
    @Timed
    public @ResponseBody byte[] getOpenedEventsInPdf(HttpServletResponse response) {
        response.setHeader("Content-Disposition", "inline; filename=file.pdf");
        response.setContentType("application/pdf");
    // get file in bytearray from my custom service in backend
        byte[] file = jasperReportsService.getOpenedEventsReport(ReportFormat.PDF);
        return file;
    }
    

    JS /角度控制器;

    $scope.getPdf = function(){
      $http.get('/api/reports/pdf', {responseType: 'arraybuffer'})
      .success(function (data) {
        var file = new Blob([data], {type: 'application/pdf'});
        var fileURL = URL.createObjectURL(file);
        window.open(fileURL);
      });
    }
    

    HTML片段:

    <a ng-click="getPdf()">Show PDF</a>
    
  • 0

    对于“浏览器兼容性”,给定代码正常工作:从beck-end控制器端获取字节数组数据并在js控制器端生成文件:

    Beck-end controller

    @RequestMapping(value = "/getPDF", method = RequestMethod.GET)
    public byte[] getEvalutaionResultPDF()  {        
            byte[] data = //get byte Array from back-end service
            return data;
    }
    

    JS Service

    var getPdfFile = function(){
            return $http.get("getPDF", {responseType: 'arraybuffer'});
    };
    

    JS controller

    $scope.pdfFile = function() {
            service.getPdfFile().then(function (data) {
    
                //for browser compatibility  
                var ieEDGE = navigator.userAgent.match(/Edge/g);
                var ie = navigator.userAgent.match(/.NET/g); // IE 11+
                var oldIE = navigator.userAgent.match(/MSIE/g); 
                var name = "file";
                var blob = new window.Blob([data.data], { type: 'application/pdf' });
    
                if (ie || oldIE || ieEDGE) {
                    var fileName = name+'.pdf';
                    window.navigator.msSaveBlob(blob, fileName);
                }
                else {
                    var file = new Blob([ data.data ], {
                        type : 'application/pdf'
                    });
                    var fileURL = URL.createObjectURL(file);
                    var a         = document.createElement('a');
                    a.href        = fileURL; 
                    a.target      = '_blank';
                    a.download    = name+'.pdf';
                    document.body.appendChild(a);
                    a.click();
                }
            },
            function(error) {
                //error
            });
        };
    
  • 2

    在以下链接中,您应该找到答案:

    AngularJS Display PDF (byte[]) received from Spring(@RestController) + jasper report

    在此链接中,您可以找到如何使用angularjs在iframe中显示pdf . 使用spring和jasper报告从API rest接收pdf .

相关问题