java - 尝试从 URL 打开 PDF 文件时,浏览器上会显示一些二进制数据

标签 java angularjs pdf jsoup

我正在开发java应用程序。我想在网页中打开一个pdf文件,应该在IE和chrome中打开。我已经调查了很多并尝试使用JSoup API。下面是html到java Controller 获取pdf文件并在网络上加载的完整流程页。问题是,当我指向的 URL 是 PDF 时,它会在 UI 上显示某种二进制格式。除了 PDF 之外,如果我使用下面的 java Controller 中显示的相同代码指向 pptx 或 xslx,它将打开该文件。关于如何使用 java 和 angularjs 在浏览器中从 URL 打开 PDF 文件有什么建议吗?

html代码:

   <div class="tab-content" ng-controller="myPDFController" style="max-height: 600px;">
    <div ng-bind-html="trustedHtml"  style="width: 100%; height: 600px;"></div>
    </div>

js代码:

app.controller('myPDFController', function ($scope, MyService) {

    MyService.getPDFContentFromURL().then(
        function (response) {
            $scope.content = response;
            $scope.trustedHtml = $sce.trustAsHtml($scope.content);
        },
        function (errResponse) {

        });
});

//service call
myServiceFactory.getPDFContentFromURL = function(){
var deferred = $q.defer();
var repUrl = appURL+'/pdfFiles'+'/getFileFromURL.form';
$http.get(repUrl).then(
        function (response) {
            deferred.resolve(response.data);
        },
        function(errResponse){

        }
    );
return deferred.promise;
}

Spring Controller :

@RequestMapping(value = "/getFileFromURL", method = RequestMethod.GET, produces="text/plain")
public @ResponseBody String getHtmlStringContent() throws Exception {
//Document doc = Jsoup.connect("https://abc.xyz.com/chks/content/myPowerPPT.pptx").ignoreContentType(true).get(); //working
Document doc = Jsoup.connect("https://abc.xyz.com/chks/content/myFirst.pdf").ignoreContentType(true).get(); //opening the pdf with binary data on the UI
String htmlString = doc.toString();
return htmlString;
}

enter image description here

最佳答案

首先,您需要将responsetype设置为arraybuffer。如果您想创建数据 blob,这是必需的。因此您的代码将如下所示:

$http.get('/postUrlHere',{myParams}, {responseType:'arraybuffer'})
  .success(function (response) {
       var file = new Blob([response], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
});

下一部分是,您需要使用 $sce使 Angular 信任您的 url 的服务。这可以通过以下方式完成:

$scope.content = $sce.trustAsResourceUrl(fileURL);

不要忘记注入(inject) $sce 服务。

如果这一切都完成了,您现在可以嵌入您的 pdf:

<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>

关于java - 尝试从 URL 打开 PDF 文件时,浏览器上会显示一些二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45205372/

相关文章:

java - Java原语可以被认为是轻型对象吗

javascript - Controller 继承在 AngularJS 中是一个好的实践吗?

javascript - 如何按字母顺序获取json文件数据

html - 位置绝对 div 显示在 PDF 文件下方

c# - 在没有安装Word的情况下以编程方式将DOCX转换为PDF?

testing - 有没有一种编程方式可以使用 Adob​​e 的 PDF 渲染器将 PDF 转换为图像?

java - 为什么 Java 似乎不尊重我的类路径?

java - Android Manifest 自动生成无效权限

Java libgdx - 设置每个屏幕的方向

javascript - AngularJS 全局 Controller