- Put @Produces(“application/pdf”) on service method, with a Response return type. It means the output is a pdf file.
- Set “Content-Disposition” in Response header to tell browser pop up a download box for user to download.
1. Download PDF file in JAX-RS
Full example to download an pdf file from JAX-RS.
package com.dineshonjava.ws.rest; 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; /** * @author Dinesh Rajput * */ @Path("/pdf") public class PdfFileService { private static final String PDF_PATH = "d:mongodb.pdf"; @GET @Path("/get") @Produces("application/pdf") public Response getSalarySlipFile() { File file = new File(PDF_PATH); ResponseBuilder response = Response.ok((Object) file); response.header("Content-Disposition", "attachment; filename="mongodb_pdf_file.pdf""); return response.build(); } }
2. Test
Deploy above JAX-RS service, access this URI pattern : “http://localhost:8181/sdnext/doj/pdf/get“.
Figure : PDF file “d:mongodb.pdf” from server is prompt for user to download, with a new pdf file name “mongodb_pdf_file.pdf”
Download SourceCode
Download pdf file from JAX-RS.zip
References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service