从Spring @RestController收到的AngularJS显示PDF(字节[]) [英] AngularJS Display PDF (byte[]) received from Spring @RestController

查看:138
本文介绍了从Spring @RestController收到的AngularJS显示PDF(字节[])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My my requirement is to either display(new tab)/download/embed a PDF in my angular js app on form submit/post.

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

I do not want the server to return a unique identifier of the generated PDF and than use $window service to open a new window with it's url pointing to a server-side endpoint which returns PDf based on unique identifier. Because I need to generate the pdf on the fly (no storing in file system).

与此问题类似的问题 AngularJS:显示Blob(.pdf)在一个有角度的应用程序中,但它对我不起作用.

Similar question to this one AngularJS: Display blob (.pdf) in an angular app But it is not working for me.

我的控制器

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);
            });
        }
    } ]);

我的服务

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

        }
    });
});

其他控制器方法

@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();
    }

我的回复已登录控制台

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

推荐答案

我使用此代码,它对我有用:

I use this code and it works for me:

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/角度控制器;

JS/Angular Controller;

$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>

这篇关于从Spring @RestController收到的AngularJS显示PDF(字节[])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆