Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. My code for the service in Java is:

@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:

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).

Does anyone have any clue of what am I doing wrong?

like image 720
Theodosios Asvestopoulos Avatar asked Dec 20 '25 15:12

Theodosios Asvestopoulos


1 Answers

I'm assuming you're using a $http.get() call.

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:

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

Don't hesitate to tell me my assumptions are incorrect.

p.s.: try to avoid using .success() and instead use .then(). The former is deprecated 1.4+ and completely removed in 1.6+

like image 84
Giovani Vercauteren Avatar answered Dec 22 '25 07:12

Giovani Vercauteren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!