GWT:将PDF文档从服务器发送到客户端

问题描述:

我有一个RPC服务,其中一种方法是使用Pentaho Reporting Engine生成报告。报告是一个PDF文件。我想要做的是,当用户请求报告时,报告会发回给他并保存对话或弹出。我在我的服务方法中试过这个:GWT:将PDF文档从服务器发送到客户端

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

但它不起作用。如何做到这一点?

我这样做有点不同。我有一个单独的servlet用于生成PDF。在客户端,这样做:

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

该servlet,DownloadPDF看起来是这样的:

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

完美的作品:)在GWT客户 – jjczopek 2010-07-12 15:28:15

+0

@BJB及彼字节怎么写字节文件, gwt不支持,对吧? – Parvathy 2013-03-13 07:17:13