[ DWR Website | Web Application Index ]

File Download

This is an example of downloading files via DWR

Please enter some text to make part of a PDF download.

Text for PDF file:

The client code simply gets the value of the input text field and sends it to the UploadDownload.downloadPdfFile() server function, and when the server replies with a PDF file, we open it for download:

function downloadPdfFile() {
  var pdftext = dwr.util.getValue('pdftext');

  UploadDownload.downloadPdfFile(pdftext, {
    callback: function(url) { dwr.engine.openInDownload(url); },
    async: false // workaround IE7/8's aggressive popup blocker
  });
}
or navigate the window to show it inline on the page:
function showPdfFile() {
  var pdftext = dwr.util.getValue('pdftext');

  UploadDownload.downloadPdfFile(pdftext, {
    callback: function(url) { window.location = url + "?contentDispositionType=inline"; },
    async: false // workaround IE7/8's aggressive popup blocker
  });
}

The server function uses iText to create a PDF file, and returns it in a FileTransfer object:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

Document document = new Document();
PdfWriter.getInstance(document, buffer);

document.addCreator("DWR.war using iText");
document.open();
document.add(new Paragraph(contents));
document.close();

return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray());

HTML source:

<input type="text" id="pdftext" value="Hello, World" size="20"/>
<button onclick="downloadPdfFile()">Download</button>

Javascript source:

function downloadPdfFile() {
  var pdftext = dwr.util.getValue('pdftext');

  UploadDownload.downloadPdfFile(pdftext, function(data) {
    dwr.engine.openInDownload(data);
  });
}

Java source:

public FileTransfer downloadPdfFile(String contents) throws Exception {
    if (contents == null || contents.length() == 0) {
        contents = "[BLANK]";
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, buffer);

    document.addCreator("DWR.war using iText");
    document.open();
    document.add(new Paragraph(contents));
    document.close();

    return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray());
}