esthrim
esthrim

Reputation: 2140

How To Download PDF file using Jersey?

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 !!

Upvotes: 16

Views: 18491

Answers (3)

Joseph Helfert
Joseph Helfert

Reputation: 421

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();
}

Upvotes: 13

MattiasH
MattiasH

Reputation: 423

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();
}

Upvotes: 1

Qwerky
Qwerky

Reputation: 18455

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.

Upvotes: 3

Related Questions