2

I have a servlet in an GWT app thats creates a PDF file with the data given with the post request and sends the responst back:

public void service(HttpServletRequest request, HttpServletResponse response) {
        try {
            String text = request.getParameter("text");
            if (text == null || text.trim().length() == 0) {
                text = "no data";
            }

            //PDF Creation with iText
            Document document = new Document();
            ByteArrayOutputStream b = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, b);
            document.open();
            document.add(new Paragraph(text));
            document.close();

            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control",
                    "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setContentType("application/pdf");

            response.setContentLength(b.size());
            OutputStream os = response.getOutputStream();
            b.writeTo(os);
            os.flush();
            os.close();

        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }

I want to show the created PDF to the User. I got this far on the client:

final RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
                GWT.getModuleBaseURL() + "PdfServlet");

    rb.setHeader("Content-type", "application/x-www-form-urlencoded");
    StringBuffer postData = new StringBuffer();
    postData.append(URL.encode("text")).append("=")
            .append(URL.encode(Text));

        rb.setRequestData(postData.toString());
        rb.setCallback(new RequestCallback() {

            @Override
            public void onResponseReceived(Request request,
                    Response response) {
                if (200 == response.getStatusCode()) {
                    //What to do here?
                } else {
                    //TODO:Something
                }
            }

            @Override
            public void onError(Request request, Throwable exception) {
                /TODO:...

            }
        });
        try {
            rb.send();
        } catch (RequestException e) {
            e.printStackTrace();
        }

So my question is: How do I show this PDF to the user? All i managaged to do is show the pdf with "no data" in it..

Thank you for you help :)

3 Answers 3

3

Instead of using a RequestBuilder, you can simply use Window.Location.setUrl(yourDowloadUrl?key=value) and include your parameters in the query String. Note however that you must set the Content-disposition header: attachment header so the browser will prompt you to save or open the file, and not replace your GWT app. Better even, create a hidden iframe in your html page, and call setUrl on that widget.

The downside of using this approach is that it doesn't allow your client code to capture feedback if something goes wrong server-side and instead of a pdf the call returns HTML with an error string from your web server. If that's very important to you, you should use a polling mechanism that requests the document, which is then produced and saved on the server, and checks every n seconds whether there is something to download. I have implemented something like this, which also prevents timeout issues with large documents. Let me know if you're interested

4
  • Hello,thank you for your answer :) I accidently posted a code with some errors ;) I use the Post method - so I can't use the URL for passing the data to the server. Do you know a way to show the response to the post requerst as a PDF?
    – Morious
    Commented Mar 24, 2012 at 15:50
  • Well, you can use a com.google.gwt.user.client.ui.FormPanel which posts your request using the POST method. You can catch the result with an addSubmitCompleteHandler. However, the client expects a String result and not a PDF. You could save the PDF server-side and return a unique id to it, which the GWT client then uses in a regular GET request: someIFrame.setUrl(acme.com/servlet?id=12345) Commented Mar 24, 2012 at 16:05
  • Allright... I'll go with GET then like you mentioned before. :) It's working that way.
    – Morious
    Commented Mar 26, 2012 at 7:54
  • did you ever find a way to do this via a POST method - i'm hitting the same problem - the one we have now with the GET works fine, but we want to create a pdf from a JSON string that we use a POST method to send to the server - i'm having some serious trouble finding out how to do it with the POST. thanks. Commented Nov 7, 2012 at 17:31
3

you should create pdf file from your servlet and stored at somewhere on server. You need to return file path where you stored on the server. And now from GWT you can prompt window to user to download file. Below is the example for downloading file from GWT:

Window.open(GWT.getHostPageBaseURL() + your return path from server, "", "");
2
  • Thank you :) I managed to open the file in the browser without storing it on the server. With the code shown above and youre code the suggestion it works fine.
    – Morious
    Commented Mar 26, 2012 at 7:56
  • Hello Morious. What was your final solution? Did you end up using the RequestBuilder? Commented Jun 7, 2012 at 12:45
1

I could displayed the created pdf without the need to save the file on the server and keep unique key. It works on Chrome but according to some posts it might be a problems on some old browsers.

Window.open("data:application/pdf;base64," + result, cRFTitle.replace(" ", "_") + ".pdf", "enabled");

As suggested the Result need to be Base64 encoded

B.

Not the answer you're looking for? Browse other questions tagged or ask your own question.