Tutorial :GWT: Sending PDF document from server to client



Question:

I have an RPC service and one of the method is generating a report using Pentaho Reporting Engine. Report is an PDF file. What I'd like to do, is when user request a report, the report is sent back to him and save dialog or sth pops up. I tried this inside my service method:

Resource res = manager.createDirectly(new URL(reportUrl), MasterReport.class);              MasterReport report = (MasterReport) res.getResource();              report.getParameterValues().put("journalName", "FooBar");              this.getThreadLocalResponse().setContentType("application/pdf");              PdfReportUtil.createPDF(report, this.getThreadLocalResponse().getOutputStream());  

But it doesn't work. How it can be done?


Solution:1

I do it a little bit differently. I've got a separate servlet that I use to generate the PDF. On the client, do something like:

Cookies.setCookie(set what ever stuff PDF needs...);  Window.open(GWT.getModuleBaseURL() + "DownloadPDF", "", "");  

The servlet, DownloadPDF looks something like this:

public class DownloadPDF extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response) {      Cookie[] cookies = request.getCookies();      try {          // get cookies, generate PDF.          // If PDF is generated to to temp file, read it          byte[] bytes = getFile(name);       sendPDF(response, bytes, name);      } catch (Exception ex) {          // do something here      }  }    byte[] getFile(String filename) {        byte[] bytes = null;        try {          java.io.File file = new java.io.File(filename);          FileInputStream fis = new FileInputStream(file);          bytes = new byte[(int) file.length()];          fis.read(bytes);      } catch (Exception e) {          e.printStackTrace();      }        return bytes;  }    void sendPDF(HttpServletResponse response, byte[] bytes, String name) throws IOException {      ServletOutputStream stream = null;        stream = response.getOutputStream();      response.setContentType("application/pdf");      response.addHeader("Content-Type", "application/pdf");      response.addHeader("Content-Disposition", "inline; filename=" + name);      response.setContentLength((int) bytes.length);      stream.write(bytes);      stream.close();  }  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »