开发者

GWT: Sending PDF document from server to client

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 w开发者_如何学Chen 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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜