How To Download PDF file using Jersey?

17,374

Solution 1

You can't just give a File as the entity, it doesn't work like that.

You need to read the file yourself and give the data (as a byte[]) as the entity.

Edit:
You might also want to look at streaming the output. This has two advantages; 1) it allows you to use serve files without the memory overhead of having to read the whole file and 2) it starts sending data to the client straight away without you having to read the whole file first. See https://stackoverflow.com/a/3503704/443515 for an example of streaming.

Solution 2

Mkyong always delivers. Looks like the only thing you are missing is the correct response header.

http://www.mkyong.com/webservices/jax-rs/download-excel-file-from-jax-rs/

@GET
@Path("/get")
@Produces("application/pdf")
public Response getFile() {
    File file = new File(FILE_PATH);
    ResponseBuilder response = Response.ok((Object) file);
    response.header("Content-Disposition","attachment; filename=test.pdf");
    return response.build();
}

Solution 3

For future visitors,

This will find the blob located at the passed ID and return it as a PDF document in the browser(assuming it's a pdf stored in the database):

@Path("Download/{id}")
@GET
@Produces("application/pdf")
public Response getPDF(@PathParam("id") Long id) throws Exception {
    Entity entity = em.find(ClientCase.class, id);
    return Response
            .ok()
            .type("application/pdf")
            .entity(entity.getDocument())
            .build();
}
Share:
17,374
esthrim
Author by

esthrim

Updated on June 07, 2022

Comments

  • esthrim
    esthrim almost 2 years

    I need to download pdf file using Jersey Web Services i already do the following but the file size received is always 0 (zero).

     @Produces({"application/pdf"})
     @GET
     @Path("/pdfsample")
     public Response getPDF()  {
    
        File f = new File("D:/Reports/Output/Testing.pdf");
        return Response.ok(f, "application/pdf").build();
    
     }
    

    Please help to do the correct way, thanks !!