PDF文件无法在Spring上呈现HTML

时间:2016-07-12 23:36:16

标签: angularjs spring pdf

我试图在浏览器中从Spring控制器渲染pdf文件。我的Controller返回数据,但不呈现pdf。我在同一页面上的文本文件有效。请指教。

    @RequestMapping(value = "/showpdf", method = RequestMethod.POST)
    @ResponseBody
    public void showPDFFile(@RequestBody FilePath filePath, final HttpServletResponse response) throws IOException {
                File file = new File(filePath);

                response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + file.getName() +"\""));
            response.setContentLength((int)file.length());

            InputStream inputStream = new FileInputStream(file);
            OutputStream output = response.getOutputStream();
            IOUtils.copy(inputStream, output);
            output.flush();

}

My Frontend Angular控制器执行简单的帖子请求:

$http.post('/showpdf', selectedFile).success(
                            function(response) {
                                console.log(response);
                            });

我的HTML页面:

<!DOCTYPE html>
<html>

<body ng-controller="reportController">
<div class="table-responsive">
  <table class="table table-striped table-condensed table-hover">
    <tbody>
    <tr ng-repeat="x in data track by $index">
      <td ng-repeat="y in x track by $index">{{ y }}</td>
    </tr>
   </tbody>
  </table>
</div>
</body>
</html>

服务器的响应是200,我能够在浏览器工具中看到字节数据。

1 个答案:

答案 0 :(得分:0)

我更改了代码以使用AngularJS Blob来渲染pdf。无法让这篇文章中的代码工作。希望这有助于某人。

@RequestMapping(value = "/showpdf", method = RequestMethod.POST, produces="application/octet-stream")
        @ResponseBody
        public byte[] showPDFFile(@RequestBody FilePath filePath, final HttpServletResponse response) throws IOException {
                  return org.apache.commons.io.FileUtils.readFileToByteArray(file);             
    }

HTML:

<div>
    <object data="{{content}}" type="application/pdf" style="width: 100%; height: 1000px;"></object>
</div>

角度控制器:

$http.post('/showpdf',{responseType: 'arrayBuffer'}).success(
                            function(response) {
                                console.log(response);
                                var file = new Blob([response], {type: 'application/pdf'});
                                   var fileURL = URL.createObjectURL(file);
                                   $scope.content = $sce.trustAsResourceUrl(fileURL);

                            });