Monday, September 14, 2015

Downloading data in PDF, XLS, WORD format in GWT

hree step are needed to perform operation to download the data in PDF, XLS, WORD format in GWT
Step -1 :-
At client side set the url from where we are going to download the data with file name as given below.

String url = GWT.getModuleBaseURL() + "downloadService?fileInfo1=" + "SiddhuFile";
Window.open( url, "_blank", "status=0,toolbar=0,menubar=0,location=0");


Step -2 :-

Make sure to enter the servlet mapping in web.xml


downloadService
com.test.pdf.server.DownloadServlet


downloadService
/testpdffileproject/downloadService


Step -3 :- Create a servlet that will do the functinality of downloading the data from server side to client side.

protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
{

String fileName = req.getParameter( "fileInfo1" );
ServletOutputStream out = resp.getOutputStream(); 
int BUFFER = 1024 * 100;
String reportContents = getServletContext().getServerInfo();
//for PDF
resp.setContentType("application/pdf");
resp.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");

//for CVS files
//resp.setContentType("text/csv"); 
//resp.setHeader("Content-Disposition", "attachment; filename="+ fileName + ".csv"); 
   
//for Word Document
//resp.setContentType("text/doc"); 
//resp.setHeader("Content-Disposition", "attachment; filename="+ fileName + ".doc"); 

resp.setContentLength( Long.valueOf( reportContents.length() ).intValue()); 
resp.setBufferSize(BUFFER);
out.write(reportContents.getBytes()); 
out.flush(); 
out.close(); 


}

Note:- Code to download the data in xls and word is also attached. Please uncomment it if you want to download the data in specific format.


No comments: