简体   繁体   English

使用javax.ws和angular打开pdf文件

[英]Open a pdf file using javax.ws and angular

I am trying to open a PDF file, saved in the server, using a Java Restful service and angularjs. 我正在尝试使用Java Restful服务和angularjs打开保存在服务器中的PDF文件。 My code for the service in Java is: 我在Java中的服务代码是:

@GET
@Path("/getPDF")
@Produces("application/pdf")
public Response getPDF() throws FileNotFoundException {
    File file = new File("/path/to/file.pdf");
    FileInputStream fileInputStream;
    fileInputStream = new FileInputStream(file);
    long contentLength = file.length();
    ResponseBuilder responseBuilder = Response.ok((Object) fileInputStream);
    responseBuilder.type("application/pdf");
    responseBuilder.header("Content-Disposition", "inline; filename=file.pdf");
    responseBuilder.header("Content-Length", contentLength);
    responseBuilder.header("charset", "utf-8");
    return responseBuilder.build();
}

Once the Response is returned I handle the request with angularjs: 一旦返回Response,我使用angularjs处理请求:

MyJavaService.getPDF().success(function(data){
    var file = new Blob([data], {type: 'application/pdf'});
    var fileURL = URL.createObjectURL(file);
    $window.open(fileURL);
});

The result is that a new window opens, with the same number of pages like the PDF file (correct), but the content is not displayed and all the pages are white (not correct). 结果是打开一个新窗口,页面数量与PDF文件相同(正确),但不显示内容,所有页面都是白色(不正确)。

Does anyone have any clue of what am I doing wrong? 有没有人知道我做错了什么?

I'm assuming you're using a $http.get() call. 我假设你正在使用$ http.get()调用。

You probably having something along the lines of: 你可能有以下几点:

$http.get(<URL>, {params: <stuff>})

You need to tell angular that the responseType is an arrayBuffer like so: 你需要告诉angular,responseType是一个arrayBuffer,如下所示:

$http.get(<URL>, {responseType: 'arraybuffer', params: <stuff>})

Don't hesitate to tell me my assumptions are incorrect. 不要犹豫,告诉我我的假设是不正确的。

ps: try to avoid using .success() and instead use .then(). ps:尽量避免使用.success()而是使用.then()。 The former is deprecated 1.4+ and completely removed in 1.6+ 前者被弃用1.4+并在1.6+中完全删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM