Main Tutorials

Download pdf file from JAX-RS

In JAX-RS, for pdf file, annotate the method with @Produces("application/pdf") :

  1. Put @Produces(“application/pdf”) on service method.
  2. Set “Content-Disposition” in Response header to prompt a download box.

1. Download Pdf file in JAX-RS

Full example to download a pdf file from JAX-RS.


import java.io.File;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

@Path("/pdf")
public class PdfService {

	private static final String FILE_PATH = "c:\\Android-Book.pdf";

	@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=new-android-book.pdf");
		return response.build();

	}

}

2. Demo

Access this URI pattern : “/pdf/get“.

Figure : Pdf file “c:\\Android-Book.pdf” from server is prompted for user to download, with a new file name “new-android-book.pdf

download pdf file from server

Download Source Code

Download it – JAX-RS-Download-Pdf-File-Example.zip (6 KB)

References

  1. JAX-RS @Produces JavaDoc
  2. List of the Application types

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
12 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Andrea
10 years ago

I’ve been developing a web application and stumbled on something like ten of your articles when searching for solutions to my issues. You just saved my life.

Suman
3 years ago

Hi ,

I have simiar requirement but instard of single pdf, i have mutiple pdfs to be download. Any input is very much helpful.

Note: Content-Disposition is not a requriement, since the consumer is also a java application

ZHAID
5 years ago

eres la mera vena

Warlord
6 years ago

Instead of File if we have a stream, how to download?

Antony Paul Raj A
7 years ago

Can I use @POST instead of @GET? Please help if anybody has answer.

asd
6 years ago

Yes you can use POST, if you really want to POST pdf towards server side.

Diego de Pablos
8 years ago

Great!!

sec
8 years ago

i just recive 404 error when i try to open the link !

Srini
9 years ago

Same here, thanks, its pretty handy. Meanwhile your blogs are really helpful.
Keep up your good work !!!

Nassimou
11 years ago

you are a big man.
Thank’s

sebastian
12 years ago

Can i use @POST instead of @GET , i am sending some parameters? Please help

yash pgdost
8 years ago

Useful, Thanks!