我正在开发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;
}
最佳答案
首先,您需要将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/