Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

javascript - How to display PDF (Blob) on iOS sent from my angularjs app

My Angular 1.5 application connect to a Java/Tomcat/Spring backend server via REST.

One REST service generates PDF and send it to the client. It works fine on DEsktop browsers (FF, Chrome at least) but I cannot see the PDF content on iOS (ipad for instance) whatever the browser I am using (Chrome, Safari..)

Here is the Angular Code :

$http.get("/displayPdf", {responseType: 'arraybuffer', params: {id: 1}}).
 success(function(data) {
   var blob = new Blob([data], {type 'application/pdf'});
   var objectUrl =  window.URL.createObjectURL(blob);
   window.open(objectUrl);
 }
);

The Spring/Jax-RS code is :

@GET
@Path("displayPdf")
@Produces("application/pdf")
Response displayPdf(@QueryParam("id") Long id) {
  byte[] bytes = service.generatePdf(); 
  return javax.ws.rs.core.Response.ok().
    entity(bytes).
    header("Content-Type", "pdf").
    header("Content-Disposition", "attachment; filename='test.pdf'").
    build();
}

I have done my research here for instance(AngularJS: Display blob (.pdf) in an angular app) but could not find an appropriate solution.

So please, do you know what should I do to display the generated PDF to my iPad/iPhone end-users ?

Thanks a lot

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

None of the solutions proposed above did work for me.

The main issue comes from URL that wasn't retrieved correctly in iOS. The following code do the correct work :

window.URL = window.URL || window.webkitURL;

Also even with this, it did not work on Chrome iOS, neither Opera iOS...so after digging the internet and inspired with the following questions :

... I finally ended up with the following code (working on all iOS browsers except FF on iOS) :

if (window.navigator.msSaveOrOpenBlob) { //IE 11+
  window.navigator.msSaveOrOpenBlob(blob, "my.pdf");
} else if (userAgent.match('FxiOS')) { //FF iOS
  alert("Cannot display on FF iOS");
}
} else if (userAgent.match('CriOS')) { //Chrome iOS
  var reader = new FileReader();
  reader.onloadend = function () { $window.open(reader.result);};
  reader.readAsDataURL(blob);
} else if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)) { //Safari & Opera iOS
  var url = $window.URL.createObjectURL(blob);
  window.location.href = url;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...