使用spring MVC返回生成的pdf with angularjs

时间:2015-11-17 20:22:13

标签: angularjs spring spring-mvc pdf wkhtmltopdf

我正在尝试与Return generated pdf using spring MVC

中的相同

但我正在使用wkhtmltopdf所以我修改了上述问题的答案,直到我得到这样的东西。

@RequestMapping(value = "/createhtml2", method = RequestMethod.POST)
public ResponseEntity<byte[]> getPDF() throws IOException {


    try {

        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", " cd C:\\Program Files\\wkhtmltopdf\\bin && wkhtmltopdf.exe "
                + "http://google.com C:\\test\\Google.pdf");

        pb.start();

    } catch (Exception e) {
        System.out.println(e);
    }


    Path pdfPath = Paths.get("C:\\test\\Google.pdf");
    byte[] pdf = Files.readAllBytes(pdfPath);


    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);
    return response;
}

我不知道上面的请求映射是否正确。但目前前端和后端不会抛出任何错误。 但是我现在如何让用户下载这个pdf文件?

这是控制器

(function () {
    'use strict';

    angular
        .module('app')
        .controller('DemoCtrl', DemoCtrl);

    DemoCtrl.$inject = ['$scope', '$http', '$localStorage' ];
    function DemoCtrl($scope, $http,$localStorage) {


        var vm = this;

        vm.add = add;

        function add() {

            $http.post('/api/createhtml2');

            console.log("Create html page")

        }

    }

})();

html页面

<div ng-controller="DemoCtrl as vm">

    <form ng-submit="vm.add()">

        <button  type="submit" class="btn btn-danger" >Create Html Page</button>

    </form>

</div>

1 个答案:

答案 0 :(得分:1)

您可以使用

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li> <a href="someurl/somefile.html"> Some file </a> 
  </li>
  <li> <a href="someurl/somefile1.html"> Some file1 </a>
  </li>
  <li> <a href="someurl/somefile2.html"> Some file2 </a>
  </li>
</ul>

<a href="someurl/someotherfile.html"> Some Other file </a>
<a href="someurl/someotherfile1.html"> Some Other file1 </a>