2016-07-12 4 views
0

Ich versuche, PDF-Datei von Spring-Controller in meinem Browser zu rendern. Mein Controller gibt die Daten zurück, aber die PDF wird nicht gerendert. Meine Textdatei auf derselben Seite funktioniert. Bitte beraten.PDF-Datei nicht im HTML-Format von Spring

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

}

Mein Frontend Angular-Controller ist eine einfache Post-Anforderung:

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

Meine HTML-Seite:

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

Die Antwort vom Server 200 und ich bin in der Lage, Byte-Daten in Browser-Tools zu sehen.

+0

warum sind Sie mit Ajax für eine PDF-Datei? Hast du iframe probiert? – charlietfl

+0

Ich habe das auch versucht, aber der Pfad muss vom Server generiert werden, den der iframe nicht einnimmt – k19

+0

Warum wird iframe es nicht nehmen? – charlietfl

Antwort

0

Ich habe meinen Code geändert, um AngularJS Blob zum Rendern der PDF zu verwenden. Der Code in diesem Post konnte nicht verwendet werden. Hoffe, das hilft jemandem.

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

Angular Controller:

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

          });