Reputation: 117
I am working on java application. I want to open a pdf file in the webpage and should open in both IE and chrome.I have investigated a lot and tried using JSoup API.Below is the complete flow of html to java controller to get the pdf file and load on the web page. Issue is when the URL i'm pointing is an PDF, it is displaying some binary format on the UI. Other than PDF if i'm pointing to pptx or xslx with the same code shown in the java controller below, it is opening that files. Any advice how to open a PDF files from the URL in a browser using java and angularjs?
html code:
<div class="tab-content" ng-controller="myPDFController" style="max-height: 600px;">
<div ng-bind-html="trustedHtml" style="width: 100%; height: 600px;"></div>
</div>
js code:
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;
}
Upvotes: 0
Views: 1129
Reputation: 1379
First of all, you need to set the responsetype to arraybuffer. This is required if you want to create a blob of your data.So your code will look like this:
$http.get('/postUrlHere',{myParams}, {responseType:'arraybuffer'})
.success(function (response) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
});
The next part is, you need to use the $sce service to make angular trust your url. This can be done in this way:
$scope.content = $sce.trustAsResourceUrl(fileURL);
Do not forget to inject the $sce service.
If this is all done you can now embed your pdf:
<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>
Upvotes: 1